




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、第11章 網(wǎng)絡(luò)通信11.1網(wǎng)絡(luò)基礎(chǔ)知識(shí)IP地址 , 5域名 主機(jī)名(hostname)端口號(hào)(port number)80,21,23,25服務(wù)類型(service)http, telnet, ftp, smtpTCP/IP協(xié)議層次結(jié)構(gòu)15.1 TCP/UDP與Socket概述運(yùn)輸層(傳輸層)包括TCP和UDP兩種通信協(xié)議以不同的方式實(shí)現(xiàn)兩臺(tái)主機(jī)應(yīng)用程序間數(shù)據(jù)的端到端傳輸Transmission Control Protocol,傳輸控制協(xié)議,提供面向連接的、可靠的數(shù)據(jù)傳輸服務(wù),保證了端到端數(shù)據(jù)傳輸?shù)目煽啃訳ser Datagram Protocol,用戶數(shù)據(jù)報(bào)協(xié)議,提供無連接的、不可靠的數(shù)據(jù)
2、傳輸方式,沒有流量控制和確認(rèn)機(jī)制。只提供校驗(yàn)和數(shù)據(jù)完整性檢查的差錯(cuò)控制,是一種盡力而為的數(shù)據(jù)傳輸方式套接字(Socket):網(wǎng)絡(luò)計(jì)算機(jī)與應(yīng)用進(jìn)程間通信的抽象協(xié)議信源機(jī)IP地址 : 信源應(yīng)用進(jìn)程端口信宿機(jī)IP地址 : 信宿應(yīng)用進(jìn)程端口兩類傳輸協(xié)議TCP (Transport Control Protocol )面向連接的能夠提供可靠的流式數(shù)據(jù)傳輸?shù)膮f(xié)議。類似于打電話的過程。URL, URLConnection, Socket, ServerSocket等類都使用TCP協(xié)議進(jìn)行網(wǎng)絡(luò)通訊。UDP (User Datagram Protocol )非面向連接的提供不可靠的數(shù)據(jù)包式的數(shù)據(jù)傳輸?shù)膮f(xié)議。類似
3、于從郵局發(fā)送信件的過程。DatagramPacket, DatagramSocket, MulticastSocket等類使用UDP協(xié)議進(jìn)行網(wǎng)絡(luò)通訊。URL類URL(Uniform Resource Locator)統(tǒng)一資源定位器的簡稱,它表示Internet上某一資源的地址。URL的組成protocol:resourceName協(xié)議名指明獲取資源所使用的傳輸協(xié)議,如http、ftp、gopher、file等,資源名則應(yīng)該是資源的完整地址,包括主機(jī)名、端口號(hào)、文件名或文件內(nèi)部的一個(gè)引用。構(gòu)造URL對(duì)象public URL(String spec)URL urlBase = new URL( “
4、/” );public URL(URL context, String spec)URL gamelan = new URL(/pages/);URL gamelanGames = new URL(gamelan, Gamelan.game.html);URL gamelanNetwork = new URL(gamelan, G.html);構(gòu)造URL對(duì)象public URL(String protocol, String host, String file);new URL(http, , /pages/G.html);public URL(String protocol, String
5、host, int port, String file); URL gamelan =new URL(http,80,pages/Gwork.html);異常處理try URL myURL = new URL(. . .) /錯(cuò)誤URL catch (MalformedURLException e) . . . / exception handler code here . . .獲取URL對(duì)象屬性public String getProtocol( )public String getHost( )public String getPort( )public String getFile(
6、)public String getRef( )通過URL讀取WWW信息public class URLReader public static void main(String args) throws Exception URL cqu = new URL(“/);BufferedReader in = new BufferedReader(new InputStreamReader(cqu.openStream();String inputLine;while (inputLine = in.readLine() != null) System.out.println(inputLine
7、);in.close(); public final InputStream openStream() /建立輸入流通過URLConnection讀寫WWW資源一個(gè)URLConnection對(duì)象代表一個(gè)Java程序與URL資源的通訊連接。通過它可對(duì)這個(gè)URL資源讀或?qū)憽+@得URLConnection類對(duì)象 URLConnection url1.openConnection()成功,返回一個(gè)URLConnection對(duì)象不成功,拋出IOException例外URLConnection類的讀寫渠道public InputStream getInputStream()public OutputStr
8、eam getOutputStream()通過URLConnection讀寫WWW資源try URL cqu = new URL(/); URLConnectionn tc = cqu.openConnection(); catch (MalformedURLException e) / new URL() failed . . . catch (IOException e) / openConnection() failed . . .InetAddress類表示一個(gè)IP地址封裝創(chuàng)建IP地址實(shí)例:InetAddress ip1=InetAddress.getLocalHost();InetA
9、ddress ip2= InetAddress.getByName(50); InetAddress ip3=InetAddress.getByName();類方法ip1.getHostName() 獲取此 IP 地址的主機(jī)名ip1.getHostAddress() 返回 IP 地址字符串11.3 socket通訊端到端的連接與通信網(wǎng)絡(luò)上的兩個(gè)程序(進(jìn)程)通過一個(gè)雙向的通信連接實(shí)現(xiàn)數(shù)據(jù)的交換。雙向鏈路的一端稱為一個(gè)socket(套接字)socket通常用來實(shí)現(xiàn)客戶方和服務(wù)方的連接。Client-server and ServiceSocket 編程模型new Socketnew SocketS
10、erverSocketClientServerRead/Write DataRead/Write DataClose SocketClose SocketwaitrequestconnectacceptsendI/O streamreceivereceivesendclosedisconnectclose簡單的TCP通信(分析)Accept創(chuàng)建Socket和ServerSocketSocket(InetAddress address, int port);Socket(InetAddress address, int port, boolean stream);Socket(String ho
11、st, int port);Socket(String host, int port, boolean stream);ServerSocket(int port);ServerSocket(int port, int count); 102465535用戶端口, count為最大連接數(shù)客戶端Socket的建立try Socket socket=new Socket(”,2000);catch(IOException e) System.out.println(Error:+e);服務(wù)器端Socket的建立ServerSocket server=null;try server=new Serv
12、erSocket(2000);catch(IOException e) System.out.println(can not listen to :+e);Socket socket=null;try socket=server.accept();catch(IOException e) System.out.println(Error:+e);打開輸入/輸出流PrintStream os=new PrintStream(new BufferedOutputStream( socket.getOutputStream() );DataInputStream is=newDataInputStr
13、eam(socket.getInputStream();PrintWriter out=newPrintWriter(socket.getOutputStream(),true);BufferedReader in=newBufferedReader(new InputStreamReader(socket.getInputStream();關(guān)閉socketos.close();is.close();socket.close();注意關(guān)閉的順序Socket通信實(shí)例-客戶端import java.io.*;import .*;public class TalkClient public stat
14、ic void main(String args) trySocket socket=new Socket(“”,4700);BufferedReader sin=new BufferedReader(new InputStreamReader(System.in);PrintWriter os=new PrintWriter(socket.getOutputStream(); BufferedReader is=new BufferedReader( new InputStreamReader(socket.getInputStream(); String readline; readlin
15、e=sin.readLine();Socket通信實(shí)例-客戶端while(!readline.equals(“bye”)os.println(readline); os.flush(); System.out.println(“Client:”+readline); System.out.println(“Server:”+is.readLine(); readline=sin.readLine();os.close();is.close(); socket.close();catch(Exception e) System.out.println(“Error”+e);Socket通信實(shí)例-
16、服務(wù)器端public class TalkServerpublic static void main(String args) tryServerSocket server=null;try server=new ServerSocket(4700);catch(Exception e) System.out.println(“can not listen to:”+e); Socket socket=null; try socket=server.accept(); catch(Exception e) System.out.println(“Error.”+e); Socket通信實(shí)例-服
17、務(wù)器端String readline;BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream();PrintWriter os=newPrintWriter(socket.getOutputStream();BufferedReader sin=new BufferedReader(new InputStreamReader(System.in);System.out.println(“Client:”+is.readLine();readline=sin.readLine();while
18、(!readline.equals(“bye”)os.println(readline); os.flush(); System.out.println(“Server:”+readline); System.out.println(“Client:”+is.readLine(); readline=sin.readLine();Socket通信實(shí)例-服務(wù)器端os.close();is.close();socket.close();server.close();catch(Exception e)System.out.println(“Error:”+e);運(yùn)行結(jié)果Server:hello!C
19、lient:hello!Server:how are you?Client:I am fine,thank you!Client:bye.Server:bye.Thread ASocketThread BSocketServerSocketClient AClient BClient CThread CSocket多客戶機(jī)制多客戶通信實(shí)例-客戶端public class MultiTalkClient int num;public static void main(String args) trySocket socket=new Socket(“”,4700);BufferedReader
20、sin=new BufferedReader(new InputStreamReader(System.in);PrintWriter os=new PrintWriter(socket.getOutputStream(); BufferedReader is=new BufferedReader( new InputStreamReader(socket.getInputStream(); String readline; readline=sin.readLine();多客戶通信實(shí)例-客戶端while(!readline.equals(“bye”)os.println(readline);
21、 os.flush(); System.out.println(“Client:”+readline); System.out.println(“Server:”+is.readLine(); readline=sin.readLine();os.close();is.close(); socket.close();catch(Exception e) System.out.println(“Error”+e); 多客戶通信實(shí)例-服務(wù)器端服務(wù)器端程序: MultiTalkServer.javaimport java.io.*;import .*;import ServerThread;publ
22、ic class MultiTalkServerpublic static void main(String args) throws IOException ServerSocket serverSocket=null;boolean listening=true;try serverSocket=new ServerSocket(4700);catch(IOException e) System.out.println(“Could not listen on port:4700.”); 多客戶通信實(shí)例-服務(wù)器端System.exit(-1);while(listening)new Ser
23、verThread(serverSocket.accept(),clientnum).start();clientnum+; serverSocket.close();多客戶通信實(shí)例-多線程類程序ServerThread.javaimport java.io.*;import .*;public class ServerThread extends ThreadSocket socket=null;static int clientnum;public ServerThread(Socket socket,int num) this.socket=socket;clientnum=num+1;
24、public void run() tryString line;多客戶通信實(shí)例-多線程類BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream();PrintWriter os=newPrintWriter(socket.getOutputStream();BufferedReader sin=new BufferedReader(new InputStreamReader(System.in);System.out.println(“Client”+clientnum+ ”:” + i
25、s.readLine();line=sin.readLine();while(!line.equals(“bye”)os.println(line);os.flush();多客戶通信實(shí)例-多線程類 System.out.println(“Server:”+line); System.out.println(“Client:”+ clientnum + “:” is.readLine(); line=sin.readLine();os.close();is.close();socket.close();catch(Exception e) System.out.println(“Error:”+
26、e);server.close();catch(Exception e)System.out.println(“Error:”+e);11.4 UDP數(shù)據(jù)報(bào)通信UDP特點(diǎn)UDP不需要建立連接,可以向網(wǎng)絡(luò)中的任何主機(jī)發(fā)送UDP數(shù)據(jù)包UDP沒有緩沖機(jī)制和窗口機(jī)制接收數(shù)據(jù)時(shí),要保證字節(jié)數(shù)組足夠大可以利用UDP實(shí)現(xiàn)廣播和組播DatagramPacket, DatagramSocket, MulticastSocket等類使用UDP協(xié)議進(jìn)行網(wǎng)絡(luò)通訊。單播(Unicast)與多播(Multicast)單播(Unicast)指網(wǎng)絡(luò)中從源向目的地轉(zhuǎn)發(fā)單播流量的過程。單播流量地址唯一,只有一個(gè)發(fā)送方和一個(gè)接收方
27、。多播/組播(Multicast)允許一個(gè)或多個(gè)發(fā)送者(多播源)將單一的數(shù)據(jù)包同時(shí)發(fā)送到多個(gè)接收者的網(wǎng)絡(luò)技術(shù)廣播(Broadcast)網(wǎng)絡(luò)廣播指一個(gè)節(jié)點(diǎn)同時(shí)向相同域中的其它所有節(jié)點(diǎn)傳輸數(shù)據(jù)包的過程。廣播消息地址包括:本地廣播、全球廣播IP: 掩碼:本地廣播地址:55全球廣播地址:55多播/組播 概述一個(gè)多播組由若干個(gè)主機(jī)構(gòu)成,當(dāng)某源主機(jī)要將數(shù)據(jù)發(fā)送給某個(gè)多播組上的所有主機(jī)時(shí),首先需要構(gòu)造一個(gè)能夠標(biāo)識(shí)該多播組的IP數(shù)據(jù)報(bào),然后以盡力而為方式轉(zhuǎn)發(fā)給對(duì)應(yīng)多播組中的各個(gè)主機(jī)。為了標(biāo)識(shí)多播組,在TCP/IP中引入了IP多播地址,每個(gè)多播組都需要一個(gè)IP多播地址來標(biāo)識(shí)。 類別地址范圍描述局部鏈接地址55用
28、于局域網(wǎng),路由器不轉(zhuǎn)發(fā)屬于此范圍的IP包預(yù)留多播地址55用于全球范圍或網(wǎng)絡(luò)協(xié)議管理權(quán)限地址55組織內(nèi)部使用,用于限制多播范圍比較通信方式協(xié)議是否需要連接可靠性數(shù)據(jù)量應(yīng)用數(shù)據(jù)報(bào)通信UDP無連接,每個(gè)報(bào)包括源地址和目標(biāo)地址不可靠,數(shù)據(jù)會(huì)丟失64KB之內(nèi)時(shí)間服務(wù),ping程序流式通信TCP需要連接可靠,數(shù)據(jù)不會(huì)丟失大量數(shù)據(jù)http服務(wù),Telnet服務(wù),F(xiàn)tp服務(wù)數(shù)據(jù)報(bào)通信DatagramSocket( )DatagramSocket(int port)DatagramSocket(int port, InetAddress laddr)DatagramPacket(byte ibuf,int il
29、ength)DatagramPacket(byte ibuf,int ilength, InetAddress iaddr, int iport) ;數(shù)據(jù)報(bào)通信收數(shù)據(jù)報(bào):DatagramPacket packet=new DatagramPacket (buf,256);socket.receive(packet);發(fā)數(shù)據(jù)報(bào)DatagramPacket packet=new DatagramPacket (buf,buf.length,address,port);socket.send(packet);數(shù)據(jù)報(bào)通信實(shí)例-客戶端客戶方程序 QuoteClient.javaimport java.i
30、o.*;import .*;import java.util.*;public class QuoteClient public static void main(String args) throws IOException if(args.length!=1) System.out.println(“Usage:java QuoteClient ”);return;DatagramSocket socket=new DatagramSocket();數(shù)據(jù)報(bào)通信實(shí)例-客戶端/send requestByte buf=new byte256;InetAddress address=InetAd
31、dress.getByName(args 0);DatagramPacket packet=new DatagramPacket (buf,buf.length,address,4445);socket.send(packet);packet=new DatagramPacket(buf,buf.length);socket.receive(packet);String received=new String(packet.getData();System.out.println(“Quote of the Moment:”+received );socket.close();數(shù)據(jù)報(bào)通信實(shí)例-
32、服務(wù)器及多線程服務(wù)器方程序:QuoteServer.javapublic class QuoteServerpublic static void main(String args) throws java.io.IOException new QuoteServerThread().start();程序QuoteServerThread.javaimport java.io.*;import .*;import java.util.*;public class QuoteServerThread extends Thread 數(shù)據(jù)報(bào)通信實(shí)例-服務(wù)器及多線程protected DatagramS
33、ocket socket=null;protected BufferedReader in=null;protected boolean moreQuotes=true;public QuoteServerThread() throws IOException this(“QuoteServerThread”);public QuoteServerThread(String name) throws IOException super(name);socket=new DatagramSocket(4445);try in= new BufferedReader(new FileReader(
34、“ one-liners.txt”);catch(FileNotFoundException e) 數(shù)據(jù)報(bào)通信實(shí)例-服務(wù)器及多線程System.err.println(“Could not open quote file. Serving time instead.”);public void run() while(moreQuotes) try byte buf=new byte256;DatagramPacket packet=new DatagramPacket(buf,buf.length); socket.receive(packet); String dString=null;
35、if(in= =null) dString=new Date().toString();數(shù)據(jù)報(bào)通信實(shí)例-服務(wù)器及多線程else dString=getNextQuote();buf=dString.getByte();/如何獲取客戶端的IP和端口InetAddress address=packet.getAddress();int port=packet.getPort();packet=new DatagramPacket(buf,buf.length,address,port);socket.send(packet);catch(IOException e) e.printStackTra
36、ce();moreQuotes=false;socket.close();數(shù)據(jù)報(bào)通信實(shí)例-服務(wù)器及多線程protected String getNextQuotes()String returnValue=null;try if(returnValue=in.readLine()= =null) in.close( );moreQuotes=false;returnValue=“No more quotes.Goodbye.”;catch(IOEception e) returnValue=“IOException occurred in server”;return returnValue;
37、使用數(shù)據(jù)報(bào)進(jìn)行廣播通信DatagramSocket只運(yùn)行數(shù)據(jù)報(bào)發(fā)往一個(gè)目的地址MulticastSocket可以將數(shù)據(jù)報(bào)以廣播方式發(fā)送到數(shù)量不等的多個(gè)客戶端。 其思想是設(shè)置一組特殊網(wǎng)絡(luò)地址(-55 )作為多點(diǎn)廣播地址,每一個(gè)多點(diǎn)廣播地址都被看做一個(gè)組,當(dāng)客戶端需要發(fā)送、接收廣播信息時(shí),加入到該組即可。 廣播(Broadcast)網(wǎng)絡(luò)廣播指一個(gè)節(jié)點(diǎn)同時(shí)向相同域中的其它所有節(jié)點(diǎn)傳輸數(shù)據(jù)包的過程。廣播消息地址包括:本地廣播、全球廣播IP: 掩碼:本地廣播地址:55全球廣播地址:55多播/組播 概述一個(gè)多播組由若干個(gè)主機(jī)構(gòu)成,當(dāng)某源主機(jī)要將數(shù)據(jù)發(fā)送給某個(gè)多播組上的所有主機(jī)時(shí),首先需要構(gòu)造一個(gè)能夠標(biāo)識(shí)該
38、多播組的IP數(shù)據(jù)報(bào),然后以盡力而為方式轉(zhuǎn)發(fā)給對(duì)應(yīng)多播組中的各個(gè)主機(jī)。為了標(biāo)識(shí)多播組,在TCP/IP中引入了IP多播地址,每個(gè)多播組都需要一個(gè)IP多播地址來標(biāo)識(shí)。 類別地址范圍描述局部鏈接地址55用于局域網(wǎng),路由器不轉(zhuǎn)發(fā)屬于此范圍的IP包預(yù)留多播地址55用于全球范圍或網(wǎng)絡(luò)協(xié)議管理權(quán)限地址55組織內(nèi)部使用,用于限制多播范圍MulticastSocket類MulticastSocket提供了如下三個(gè)構(gòu)造方法: public MulticastSocket(): public MulticastSocket(int portNumber):使用默認(rèn)地址、指定端口來創(chuàng)建一個(gè)MulticastSocket
39、對(duì)象。 public MulticastSocket(SocketAddress bindaddr):使用指定IP地址、指定端口來創(chuàng)建一個(gè)MulticastSocket對(duì)象。創(chuàng)建一個(gè)MulticastSocket對(duì)象后,還需要使用joinGroup ( InetAddress mcastaddr)方法將該MulticastSocket加入到指定的多點(diǎn)廣播地址(組),使用leaveGroup()方法脫離一個(gè)組。廣播通信實(shí)例-客戶端客戶方程序:MulticastClient.javaimport java.io.*;import .*;import java.util.*;public class MulticastClient public static void main(String args) throws IOException MulticastSocket socket=new MulticastSocket(4446);InetAddress address=I
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 清洗地面合同范本
- 煙葉生產(chǎn)用工合同范本
- bimco 光租合同范本
- 別墅如何洽談合同范本
- 慶典布展合同范本
- 自駕活動(dòng)合同范本
- 多式聯(lián)運(yùn)合同(6篇)
- 音樂初步知識(shí)點(diǎn)
- 淘寶后臺(tái)操作流程
- 山東建筑大學(xué)《書法創(chuàng)作》2023-2024學(xué)年第二學(xué)期期末試卷
- JBT 14585-2024 信號(hào)蝶閥(正式版)
- 文具店合作意向協(xié)議書
- 中國神話故事繪本火神祝融
- 五星級(jí)酒店前廳管理常用表格
- 《養(yǎng)老護(hù)理員》-課件:老年人安全防范及相關(guān)知識(shí)
- 茶樓棋牌經(jīng)營管理方案
- 水準(zhǔn)測量記錄數(shù)據(jù)自動(dòng)生成表
- 2024年宜都市高新技術(shù)產(chǎn)業(yè)投資有限公司招聘筆試參考題庫含答案解析
- 2024年英語專業(yè)四級(jí)考試真題及詳細(xì)答案
- 初中數(shù)學(xué)八年級(jí)下冊(cè) 一次函數(shù)的概念 全市獲獎(jiǎng)
- 肺占位性病變查房
評(píng)論
0/150
提交評(píng)論