ch11_Networking_网络ppt课件.pptx

上传人:春哥&#****71; 文档编号:16977163 上传时间:2022-05-20 格式:PPTX 页数:40 大小:1.12MB
返回 下载 相关 举报
ch11_Networking_网络ppt课件.pptx_第1页
第1页 / 共40页
ch11_Networking_网络ppt课件.pptx_第2页
第2页 / 共40页
点击查看更多>>
资源描述

《ch11_Networking_网络ppt课件.pptx》由会员分享,可在线阅读,更多相关《ch11_Networking_网络ppt课件.pptx(40页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、ch11_Networking_网络Chapter 11 Networking11.1 Concept of networking 网络的概念 In a network, different computers make connections with each other and exchange information. In Java, basic networking is supported by classes in package. These classes provide system-independent network communication, including

2、 supports for connecting and retrieving files by HTTP and FTP protocols, as well as working at a lower level with sockets. Using TCP or UDP, Java programs can communicate over the Internet. 在network中,计算机相互交换信息。与网络通信相关的类在J包里。利用这些类,可以实现FTP与HTTP协议的文件传输以及sockets通信。使用TCP或UDP协议,Java程序可在互联网上交互信息。 On the in

3、ternet, resources of data, audios and images are stored in files. A resource can be something as simple as a file or a directory. Java allows you to develop clients that retrieve files on a remote host through its Web server, the Web server can be used to send the files to the clients. Web ServerLoc

4、al fileWeb BrowserApplet reads the fileInternetApplication reads the file 互联网上,数据、声音和图像等资源都以文件为单位存储。资源其实就像文件或者目录那样简单。 可以用Java编写clients端程序,用以访问远程计算机上的文件(资源)。由远程计算机的Web服务器将文件发送给客户。11.2 URL class The first thing to read a file from the internet is to locate the host computer, which holds the files. The

5、 .URL class can be used to identify the files on the Internet. In general, a URL (Uniform Resource Locator) is a pointer to a resource on the World Wide Web. As long as providing a URL to a Web browser, the files on the Internet can be located. Java programs that interact with the Internet also use

6、URLs to find the resources on the Internet. A Java programs can use class URL to provide a URL address. In a Java program, an object of URL represents a URL address. URL class has several constructors, one of them is: public URL(String spec) throws MalformedURLExceptionWhere, spec represents a URL a

7、ddress. While the URL address is wrong, or cant be resolved, an exception MalformatedURLException will be thrown.11.2 URL class 要从互联网读文件,首要的事情是定位文件所在的计算机。 .URL 类可用于文件的定位。通常,把URL (Uniform Resource Locator) 看作是WWW上的 “资源”的地址 ,只要向Web浏览器提供文件的地址,就可以定位文件。 Java程序与互联网的交互也要通过URL定位互联网上的资源实现。Java程序利用程序利用 URL 类提

8、供URL地址。地址。 Java程序中,URL类的对象代表类的对象代表URL地址,地址, URL 类有很多构造方法,其中之一是: public URL(String spec) throws MalformedURLException其中, spec是URL地址。 如果URL地址不对,或者无法地址不对,或者无法 厘清,构造方法会抛出厘清,构造方法会抛出 MalformatedURLException异常。Examplepublic URL(String spec) throws MalformedURLException The following statement creates a URL

9、 object for http:/ try URL url = new URL(http:/);catch(MalformedURLException ex) A URL has two main components:1. Protocol identifier In the above example, the protocol identifier is http (Hypertext Transfer Protocol). 2. Resource name The resource name is The protocol identifier and the resource na

10、me are separated by a colon and two forward slashes. ExampleClass URL has several useful methods.import .*;public class TryURL public static void main(String args) try URL url = new URL(http:/); System.out.println(url.getProtocol(); System.out.println(url.getHost(); System.out.println(url.getRef();

11、System.out.println(url.getDefaultPort(); catch(MalformedURLException ex) httpnull80Read resource (file) through openStream() method If you want to read resources (files), just invoke openStream() method of the URL object.To retrieve the file of an internet resource: 1. Create a URL object for the fi

12、le2. Use the openStream() method of the URL class to open an input stream to the files URL. URL url = new URL(http:/www.cs.armstrong.edu/liang/index.html); InputStream input = url.openStream(); Method openStream returns an object of InputStream class.import .URL;import java.io.*;public class ReadSou

13、rce public static void main(String args) int ch; try URL url = new URL(http:/); InputStream in=url.openStream();InputStreamReader rd=new InputStreamReader(in); while(ch=rd.read()!=-1) (char)ch); catch(IOException e) (Network error! ) /source code of the web page301 Moved Permanently301 Moved Permane

14、ntlynginx; /use BufferedReader classimport java.io.*;public class ReadSource public static void main(String args) String line; try URL url = new URL(http:/); InputStream in=url.openStream(); /byte stream InputStreamReader rd=new InputStreamReader(in); /char stream BufferedReader bf=new BufferedReade

15、r(rd); /buffered char while(line=bf.readLine()!=null) /public String readLine() System.out.println(line); catch(IOException e) (Network error!); 11.3 Socket communication 套接字通信 URLs provide a relatively high-level mechanism for accessing resources on the Internet. Sometimes programs need lower-level

16、 network communication with sockets, for example, when you write a client-server application. The client-server applications on the Internet can adopt TCP protocol. TCP provides a reliable, point-to-point communication. A socket is the combination of an IP address and a port number. A socket is one

17、end-point of a two-way communication between two programs running on the network. The socketcommunication is based on the TCP protocol. A client program and a server program establish a connection to one another. Each program binds a socket to its connection, then the client and the server reads fro

18、m and writes to the sockets bound to the connection. Socket classes are used to represent the connection between a client program and a server program.11.3 Socket classes 套接字通信 URLs 机制用于访问互联网上的资源。对于客户/服务器这样低层次的通信,需要用套接字实现。客户/服务器通信可以采用TCP协议,它提供可靠的点对点的有连接的通信。 套接字是IP地址和端口号的组合。套接字是在网络上运行的两个程序之间双向通信的端点。套

19、接字通信可以采用TCP协议。为了实现客户程序与服务器程序的通信,客户端和服务器端都要设计程序,通信双方通过套接字建立连接,并读/写数据。Socket 类用于客户/服务器程序之间建立连接与交换数据。套接字(socket)为两台计算机之间的通信提供了一种机制,客户端和服务器分别读取和写入数据到套接字,套接字实现客户与服务器的连接。11.3.1How Socket communication works 套接字通信原理 Normally, a server running on a computer has a socket that is bound to a specific port numb

20、er to tell the system to receive all data through that port. The client also needs to binds to a local port number that will be used during connecting with the server. In the socket communication, the server program keeps running and listening to the socket for a client to make a connection request.

21、 The clients request for connections to the server. After the server accepts a connection, the communication between the server and the client is conducted, the same as I/O streams. 服务器计算机的socket 绑定到一个特定的端口,用于通知系统,将从这个端口接收数据。客户计算机也要绑定到一个端口,用于与服务器的连接。在套接字(socket)通信中服务器程序要先运行,等待客户机的连接请求。客户机发出连接请求,服务器接

22、受请求后,服务器与客户机便开始通信(读/写数据),通信过程即是I/O过程。11.3.2 Ports 端口 A socket needs to bind to a port. Usually, a computer has a single physical connection to the network. All data arrives through that connection. By ports, the computer knows to which application the data forwards. The TCP and UDP protocols use por

23、ts to map incoming data to a particular process running on a computer. Data transmits over the Internet by addressing information URL to locate the computer, and by port to determine the data to and from which program (application). In fact, the computer is identified by its 32-bit IP address, and p

24、orts are identified by a 16-bit number, with which TCP delivers data to the right application. The 16-bit means the numbers range from 0 to 65,535. The port numbers ranging from 0 - 1023 are reserved for use by services such as HTTP and FTP and other system services. 11.3.2 Ports 端口 通常,计算机与网络只有一个物理连

25、接计算机与网络只有一个物理连接,网上的数据都是通过这个物理连接到达计算机的。通过端口,网上的数据能够送到通过端口,网上的数据能够送到指定的应用(程序)指定的应用(程序)。TCP和UDP协议利用端口将数据发送给计算机上正在运行的特定的应用。URL址用于定位计算机,实现数据在互联网上的传输,端口则定位具体的应用端口则定位具体的应用。 事实上,识别计算机是通过一个识别计算机是通过一个32-bit的的IP地址实现的地址实现的。识别应用(程序)则是通过一个16-bit的数(端口号)实现的。16-bit能够表示的数的范围为0-65,535。端口号01023为系统保留,例如HTTP和FTP以及其它系统设备的

26、端口号。11.4 ServerSocket and Socket classesconstructorServerSocket(int port) Socket(InetAddress address, int port) ExampleServer side;ServerSocket Listen=new ServerSocket(4321); A listening portClient side:Socket service=new Socket(“Email server”,4321);Host In J package there are Socket and ServerSocke

27、t classes. The Socket class implements the client side of a two way connection between a Java program and other program on the network. The ServerSocket class implements a socket that servers can use to listen and accept connections to clients. Useful methods of the two classesgetPort /get remote si

28、de portgetLocalPortgetInputStreamgetOutputStreamclose /close socket object The server must be running when a client starts. The server waits for a connection request from a client. To establish a server, you need to create a server socket and attach it to a port, which is where the server listens fo

29、r connections.serverclient11.4.1 Tasks of each side1. Socket in server sideTry ServerSocket srv = new ServerSocket(2000); Socket socket = srv.accept(); catch (IOException e) Read text from the socketTry BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream(); String str;

30、 while (str = rd.readLine() != null) System.out.println(str); rd.close(); catch (IOException e) 2. Socket in client sidetry Socket socket = new Socket(IPaddr, 2000); catch (Exception e) try OutputStreamWriter wr = newOutputStreamWriter(socket. getOutputStream(); wr.write(Hello);catch (IOException e)

31、 11.4.2 Data TransmissionInputStream input = socket.getInputStream();OutputStream output = socket.getOutputStream();ServerSocket svr=new ServerSocket(8000);Socket socket=svr.accept();Socket sk=new Socket(“localhost”, 8000);Connection requestInputStream input = sk.getInputStream();OutputStream output

32、 = sk.getOutputStream();Continue ServerSocket svr=new ServerSocket(8000);Socket socket=svr.accept();Socket socket=new Socket(“localhost”, 8000);socket.getInputStream socket Network socket.getOutputStream socket InputStreamOutputStreamimport java.io.*; import .*;class Sever public static void main(St

33、ring arg) int count=0; /count number of clients byte b=new byte100; InputStream in; int k; try ServerSocket server=new ServerSocket(9876); while(true) /wait for many clients Socket sc=server.accept(); in=sc.getInputStream(); k=in.read(b); System.out.print(Client message:); for(int i=0;ik;i+) System.

34、out.print(char)bi); System.out.println(); System.out.println(This is +(+count)+ client); System.out.println(Client IP:+sc.getInetAddress(); System.out.println(port:+sc.getLocalPort(); in.close(); sc.close(); catch(Exception e) Listen, accept return clients socket.Create socket.return InputStreamSeve

35、r side (ipconfig)Client side: import java.io.*;import .*;public class Client public static void main(String args) throws Exception byte a=H,e,l,l,o; OutputStream dout; Socket sc=new Socket(localhost,9876); dout=sc.getOutputStream(); dout.write(a); dout.close(); sc.close(); Only byte data, inconvenie

36、nt !Server side output:Client message:HelloThis is 1 clientClient IP:port:9876Client message:HelloThis is 2 clientClient IP:port:9876Simple program (Server side)import java.io.*;import .*;public class TcpSever public static void main(String args) throws Exception byte buffer=new byte200; InputStream

37、 is; OutputStream os; int length=0; ServerSocket ss=new ServerSocket(5000); while(true) Socket socket=ss.accept(); is=socket.getInputStream(); os=socket.getOutputStream(); length=is.read(buffer); /data read stored in buffer String str=new String(buffer,0,length); /convert byte to string System.out.p

38、rintln(str); os.write(Client, How are you?.getBytes(); /convert string to byte is.close(); os.close(); socket.close(); /read first !Simple program (Client side)import java.io.*;import .*;public class TcpClient public static void main(String args) throws Exception Socket socket=new Socket(localhost,

39、5000); OutputStream os=socket.getOutputStream(); os.write(hello world.getBytes(); InputStream is=socket.getInputStream(); byte buffer=new byte200; int length=is.read(buffer); String str=new String(buffer,0,length); System.out.println(str); is.close(); os.close(); socket.close(); write firstDealing s

40、tream (read from keyboard)BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in); InputStreamReaderThe class supports readingreading of characterscharacters from a byte input rom a byte input streamstream. A character encoding may also be specified.internetServer side: InputStreamR

41、eaderimport java.io.*; import .*;class Sever public static void main(String arg) int count=0; /count number of clients char b=new char100; InputStreamReader in; int k; try ServerSocket server=new ServerSocket(9876); while(true) Socket sc=server.accept(); in=new InputStreamReader(sc.getInputStream();

42、 k=in.read(b); /number of characters System.out.print(Client message:); for(int i=0;ik;i+) System.out.print(bi); System.out.println(); System.out.println(This is +(+count)+ client); System.out.println(Client IP:+sc.getInetAddress(); System.out.println(port:+sc.getLocalPort(); in.close(); sc.close();

43、 catch(Exception e) Server side output:Client message:HelloThis is 1 clientClient IP:port:9876Client message:HelloThis is 2 clientClient IP:port:9876Hope to read/write lines.InputStreamDealing stream (read from keyboard)BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in); intern

44、etimport java.io.*; import .*;class Server public static void main(String arg) int count=0; /count number of clients String str=null; BufferedReader in; try ServerSocket server=new ServerSocket(9876); while(true) /wait for many clients Socket sc=server.accept(); in=new BufferedReader(new InputStream

45、Reader(sc.getInputStream(); while(true) str=in.readLine(); if(str!=null) System.out.println(Client message:+ str); else break; System.out.println(This is +(+count)+ client); System.out.println(Client IP:+sc.getInetAddress(); System.out.println(port:+sc.getLocalPort(); in.close(); sc.close(); catch(E

46、xception e) InputStreamSever side: BufferedReaderinternetClient side: import java.io.*;import .*;public class Client public static void main(String args) throws Exception Socket sc=new Socket(localhost,9876); OutputStreamWriter out=new OutputStreamWriter(sc.getOutputStream(); out.write(Im a clientrn

47、); out.close(); sc.close(); Server side output:Client message:Im a clientThis is 1 clientClient IP:port:9876Client message:Im a clientThis is 2 clientClient IP:port:9876OutputStreamSummery (1) Create Socket connection(2) open input/output stream(3) read/write(4) close input/output stream(5) close So

48、cket11.5 Serving Multiple Clients 服务多个客户 Multiple clients are quite often to connect to a single server at the same time. Usually, a server runs constantly on a server computer, and clients from all over the Internet may want to connect to it. You can use threads to handle the servers multiple clien

49、ts simultaneously. The server create a thread for each connection. Here is how the server handles a connection.while (true) Socket socket = serverSocket.accept(); Thread thread = new ThreadClass(socket); thread.start();Simple talk program (server side)import .*;import java.io.*;public class TalkServ

50、er public static void main(String arg) try ServerSocket s=new ServerSocket(5432); while(true) /wait for many clients Socket s1=s.accept(); /wait for client connection new Soutput(s1).start(); /for each client create 2 threads new Sinput(s1).start(); System.out.println(Talk to clients:); catch(Except

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 大学资料

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁