安徽工程大学 Java 第10章-网络编程.ppt
Java语言程序设计马 皓11.概述2.URL应用3.Socket应用4.UDP数据报第十章 Java网络编程2概述nThe Java platform is highly regarded in part because of its suitability for writing programs that use and interact with the resources on the Internet and the World Wide Web.3概述1.AppletnApplet程序嵌在HTML文件中,通过网络下载Applet程序代码,在本地Java-enabled browser 中执行2.HTTPn通过URL类获取服务器端的HTML文件3.Socket(套接字)n实现Client/Server结构的应用4.JDBC(Java Database Connectivity)n通过网络访问关系型数据库nOracle,MS SQL,Sybase5.Servlet/JSP(Java Server Page)nWEB服务器端的动态编程4概述n网络基础-TCP/IP协议簇n网络层(Network Layer)nInternet Protocol(IP),nIP地址,32比特n传输层(Transport Layer)n传输控制协议(TCP:Transport Control Protocol)n用户数据报协议(UDP:User Datagram Protocol)n端口(Port,16比特,065535)n应用层(Application Layer)nHTTP,FTP,SMTP,POP3,Telnet,DNS TCP or UDPPort应用PortPortPortPort 数据1应用应用应用Port 数据2主机5概述nJava语言中基本网络类nPackage .URL.URLC.S.ServerS.DatagramP.DatagramS.MulticastSocket61.概述2.URL应用3.Socket应用4.UDP数据报第十章 Java网络编程7URL应用n什么是URL?n统一资源定位符(Uniform Resource Locator)na reference(an address,a pointer)to a resource on the I:/协议标识符资源名(主机名,端口号,文件名) URL(String spec)throws MalformedURLExceptionnpublic URL(String protocol,String host,String file)throws MalformedURLExceptionnpublic URL(String protocol,String host,int port,String file)throws MalformedURLExceptionn n实例方法npublic final InputStream openStream()throws IOExceptionnOpens a connection to this URL and returns an InputStream for reading from that connectionnpublic URLConnection openConnection()throws IOExceptionnReturns a URLConnection object that represents a connection to the remote object referred to by the URL 9URL应用.URL类-示例1.“http:/ URL(http:/);2.http:/ URL(http:/ URL(http,/academic/index.html);nnew URL(http,80,“/academic/index.html);10URL应用n实例import .*;import java.io.*;public class URLReader public static void main(String args)throws Exception URL pku=new URL(http:/);BufferedReader in=new BufferedReader(new InputStreamReader(pku.openStream();String inputLine;while(inputLine=in.readLine()!=null)System.out.println(inputLine);in.close();.URL类public final InputStream openStream()throws IOException11URL应用.URL类-实例2StringBuffer document=new StringBuffer();String urlString=“http:/”;try URL url=new URL(urlString);URLConnection conn=url.openConnection();BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream();String line=null;while(line=reader.readLine()!=null)document.append(line+“n”);reader.close();catch(MalformedURLException e)System.out.println(“Unable to connection to URL:”+urlString);catch(IOException e)System.out.println(“IOException when connected to URL:”+urlString);System.out.println(document.toString();.URL类openStream()is a shorthand for openConnection().getInputStream()12URL应用.URL类n操作流程1.用所要连接资源的有效 URL实例化一个 URL对象(如有问题则抛出 MalformedURLException)2.打开该 URL对象上的一个连接 3.把该连接的 InputStream 包装进 BufferedReader 以便能按行读取4.用 BufferedReader 读文档5.关闭 BufferedReader(关闭该URL)131.概述2.URL应用3.Socket应用4.UDP数据报第十章 Java网络编程14Socket应用nTCP协议n从功能上来讲,建立一个可靠的、端到端的通信连接n操作系统实现了TCP协议的内容nSocket(套接字)n代表了TCP所定义的双向通信连接的一个端点n通信双方(两台机器)n一个作为客户端,一个作为服务器端n客户/服务器的本质区别n服务器方(Server)总在监听一个特定的端口n客户(Client)则向该端口发出连接请求nWindows系统TCP/UDP连接状态的监测nnetstat-a15Socket应用.Socket类n表示TCP连接的客户方(Client),和谁连接n指定对方的IP地址和端口号npublic Socket(String host,int port)throws UnknownHostException,IOExceptionnSocket对象包括两个流nSocket代表了TCP所定义的双向通信连接的一个端点n输入流(读取通过网络进来的数据)npublic InputStream getInputStream()throws IOExceptionn输出流(将数据写入输出流中,并通过网络发送)npublic OutputStream getOutputStream()throws IOExceptionn操作步骤1.先建立连接 2.进行流的读写操作16Socket应用n对客户端对Socket进行读写-实例ServerSocketLocalhostSocketOutputStreamInputStreamInputStreamOutputStream客户端服务器端17Socket应用n对客户端对Socket进行读写-实例import .*;import java.io.*;public class SimpleClient public static void main(String args)Socket s=new Socket(“”,5432);InputStream in=s.getInputStream();DataInputStream dis=new DataInputStream(in);String st=dis.readUTF();System.out.println(st);in.close();s.close();ServerSocketLocalhostSocketOutputStreamInputStreamInputStreamOutputStream建立连接打开输入流读取输入流关闭输入流关闭连接18Socket应用.ServerSocket类nTCP连接的服务器方(Server),监听端口n等待自客户端发来的连接npublic ServerSocket(int port)throws IOExceptionn接收连接请求npublic Socket accept()throws IOExceptionnListens for a connection to be made to this socket and accepts it.The method blocks(阻塞)until a connection is maden服务器端通过所接收到的Socket对象和客户端通信nSocket代表了TCP所定义的双向通信连接的一个端点n操作步骤1.监听端口2.接收连接3.进行流的读写操作19Socket应用n对ServerSocket的实现-实例ServerSocketLocalhostSocketOutputStreamInputStreamInputStreamOutputStream客户端服务器端20Socket应用ServerSocket s=null;String hello=“Hello World!”;try s=new ServerSocket(5432);catch(IOException e)System.out.println(e);System.exit(1);while(true)try Socket cs=s.accept();OutputStream out =cs.getOutputStream();DataOutputStream dos=new DataOutputStream(out);dos.writeUTF(hello);out.close();cs.close();catch(IOException e)System.out.println(e);ServerSocketLocalhostSocketOutputStreamInputStreamInputStreamOutputStream接收连接打开输出流写入输出流关闭输出流关闭连接监听端口21Socket应用n客户端与服务器端的实现客户端服务器端22Socket应用n多线程的服务器实现n为每个客户的连接(Socket)分配一个线程,让其独立处理n两种实现方式1.作为java.lang.Thread类的子类2.实现java.lang.Runnable接口Thread 1Thread nClient 1SocketPServerSocketClient nSocket12312323Socket应用n多线程的服务器实现-实例ServerSocket s=new ServerSocket(5432);boolean listening=true;while(listening)new ServerThread(s.accept().start();s.close();class ServerThread extends Thread public void run()241.概述2.URL应用3.Socket应用4.UDP数据报第十章 Java网络编程25UDP数据报应用n数据报(Datagram)n通过UDP协议发送数据报,各个数据报是相互独立,数据报是否到达(可能丢失)、到达时间、到达顺序不能保证.DatagramPacketn构造一个要发送/接收的数据报对象.DatagramSocketn构造一个用于发送/接收数据报的socket对象.MulticastSocketn构造一个用于发送/接收组播数据报的socket对象26UDP数据报应用n数据报(Datagram)的收/发流程n发送1.构造用于发送的数据报对象(指定要发送的地址和端口号)npublic DatagramPacket(byte buf,int length,InetAddress address,int port)2.构造用于发送数据报的socket对象npublic DatagramSocket()throws SocketException3.发送npublic void send(DatagramPacket p)throws IOExceptionn接收1.构造用于接收的数据报对象npublic DatagramPacket(byte buf,int length)2.构造用于接收数据报的socket对象npublic DatagramSocket(int port)throws SocketException3.接收npublic void receive(DatagramPacket p)throws IOExceptionnThis method blocks until a datagram is received27UDP数据报应用n数据报客户端的实现-实例DatagramSocketLocalhostDatagramSocketDatagram packet客户端服务器端28UDP数据报应用n数据报客户端的实现DatagramSocket socket=new DatagramSocket();String s=“hello”;byte buf=s.getBytes();InetAddress address=InetAddress.getByName(“”);DatagramPacket packet=new DatagramPacket(buf,buf.length,address,6666);socket.send(packet);packet=new DatagramPacket(buf,buf.length);socket.receive(packet);String received=new String(packet.getData();System.out.println(“Received:+received);socket.close();DatagramSocketLocalhostDatagramSocketDatagram packetpublic DatagramPacket(byte buf,int length,InetAddress address,int port)public DatagramPacket(byte buf,int length)public byte getData()public DatagramSocket()throws SocketExceptionpublic void receive(DatagramPacket p)throws IOExceptionpublic void send(DatagramPacket p)throws IOException构造数据报Socket构造发送数据报,发送要发送的地址构造接收数据报关闭数据报Socket从数据报中获取数据接收数据报29UDP数据报应用n数据报服务端的实现-实例DatagramSocketLocalhostDatagramSocketDatagram packet客户端服务器端30UDP数据报应用n数据报服务端的实现DatagramSocket socket=new DatagramSocket(6666);byte buf=new byte256;DatagramPacket packet=new DatagramPacket(buf,buf.length);socket.receive(packet);String received=new String(packet.getData().trim();InetAddress address=packet.getAddress();int port=packet.getPort();packet=new DatagramPacket(buf,buf.length,address,port);socket.send(packet);socket.close();DatagramSocketLocalhostDatagramSocketDatagram packetpublic DatagramPacket(byte buf,int length,InetAddress address,int port)public DatagramPacket(byte buf,int length)public byte getData()public InetAddress getAddress()public int getPort()public DatagramSocket(int port)throws SocketExceptionpublic void receive(DatagramPacket p)throws IOExceptionpublic void send(DatagramPacket p)throws IOException构造数据报Socket,监听端口构造发送数据报得到要发送的地址构造接收数据报关闭数据报Socket接收数据报接收到的字符串得到要发送的端口发送数据报31UDP数据报应用n组播数据报(Multicast Datagram)n特定的IP地址(组播地址)n224.0.0.0 239.255.255.255n该IP地址作为组的标识n一个应用向一个组播地址/组发送一个消息,所有组成员都能从该组播地址和端口上接收到该消息。该应用可以不是组成员n类似与邮件列表n当一个应用成为一个组播地址/端口的成员,则它可以接收到其他成员发送的数据报32UDP数据报应用n组播数据报(Multicast Datagram).MulticastSocket类n指定组播地址和端口n加入组/离开组5组播地址组(224.0.0.1)124加入组离开组333UDP数据报应用n组播数据报(Multicast Datagram)的实例String msg=Hello;InetAddress grp=InetAddress.getByName(228.5.6.7);MulticastSocket s=new MulticastSocket(6789);s.joinGroup(grp);DatagramPacket hi=new DatagramPacket(msg.getBytes(),msg.length(),grp,6789);s.send(hi);byte buf=new byte1000;DatagramPacket recv=new DatagramPacket(buf,buf.length);s.receive(recv);s.leaveGroup(grp);s.close();.MulticastSocket extends DatagramSocketnpublic MulticastSocket(int port)throws IOExceptionnpublic void joinGroup(InetAddress mcastaddr)throws IOExceptionnpublic void leaveGroup(InetAddress mcastaddr)throws IOExceptionnpublic void send(DatagramPacket p)throws IOExceptionnpublic void receive(DatagramPacket p)throws IOException定义一个组播地址构造接收数据报构造组播Socket关闭数据报Socket加入该组构造发送数据报,发送接收数据报离开该组34第十章 结束!35