Java網(wǎng)絡編程技術-03_第1頁
Java網(wǎng)絡編程技術-03_第2頁
Java網(wǎng)絡編程技術-03_第3頁
Java網(wǎng)絡編程技術-03_第4頁
Java網(wǎng)絡編程技術-03_第5頁
已閱讀5頁,還剩24頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

第3章UDP協(xié)議網(wǎng)絡編程1UDP協(xié)議是無連接的協(xié)議,它以數(shù)據(jù)報作為數(shù)據(jù)傳輸?shù)妮d體。數(shù)據(jù)報是一個在網(wǎng)絡上發(fā)送的獨立信息,它的到達、到達時間以及內容本身等都不能得到保證。數(shù)據(jù)報的大小是受限制的,每個數(shù)據(jù)報的大小限定在64KB以內。UDP協(xié)議無需在發(fā)送方和接收方建立連接,但也可以先建立連接。數(shù)據(jù)報在網(wǎng)上可以以任何可能的路徑傳往目的地。在Java中,基于UDP協(xié)議實現(xiàn)網(wǎng)絡通信的類有三個:用于表達通信數(shù)據(jù)的數(shù)據(jù)報類DatagramPacket

用于進行端到端通信的類DatagramSocket

用于組播通信的類MulticastSocket。3.1數(shù)據(jù)報通信datagramserverclient2類DatagramPacket構造方法publicDatagramPacket(byte[]

buf,int

length)publicDatagramPacket(byte[]

buf,int

offset,int

length):這兩個方法用于接收數(shù)據(jù)publicDatagramPacket(byte[]

buf,int

length,InetAddressaddress,int

port)publicDatagramPacket(byte[]

buf,int

offset,int

length,InetAddress

address,int

port):這兩個方法用于發(fā)送數(shù)據(jù)獲取數(shù)據(jù)——獲取接收報中的信息publicInetAddressgetAddress()publicbyte[]getData()publicintgetLength()publicintgetOffset()publicintgetPort()設置數(shù)據(jù)——設置發(fā)送報中的信息setAddress(InetAddress

iaddr)、setPort(int

iport)、setData(byte[]

buf)、setData(byte[]

buf,int

offset,int

length)、setLength(int

length)3.2數(shù)據(jù)報通信 ——數(shù)據(jù)報3類DatagramSocket構造方法publicDatagramSocket()publicDatagramSocket(int

port):在指定的端口通信publicDatagramSocket(int

port,InetAddress

laddr):在指定的地點運行這三個方法都將拋出例外SocketException,程序中需要捕獲處理。最主要的方法——發(fā)送與接收數(shù)據(jù)報publicvoidreceive(DatagramPacket

p)publicvoidsend(DatagramPacket

p)這兩個方法都將拋出例外IOException,程序中需要捕獲處理。其他方法publicvoidconnect(InetAddress

address,int

port):與指定的機器通信publicvoiddisconnect():關閉與指定機器的連接publicvoidclose():關閉Socket3.3數(shù)據(jù)報通信 ——點到點通信4建立數(shù)據(jù)報socket();建立一個數(shù)據(jù)報packet等待請求報文建立數(shù)據(jù)報socket建立一個請求數(shù)據(jù)報發(fā)出請求獲得對方地址構成信息包發(fā)送出去創(chuàng)建接收包等待接收接收端發(fā)送端5SingleUDPClient.java看看這個點到點通信程序的運行效果:2、客戶端〔接收端〕SingleUDPServer.java1、效勞器端〔發(fā)送端〕6發(fā)送端發(fā)出數(shù)據(jù)報的標準步驟:1.定義數(shù)據(jù)成員DatagramSocketsocket;DatagramPacketpacket;InetAddressaddress;(用來存放接收方的地址)intport;(用來存放接收方的端口號)2.創(chuàng)立數(shù)據(jù)報Socket對象try{socket=newDatagramSocket(4445);}e){}socket綁定到一個本地的可用端口,等待接收客戶的請求。73.分配并填寫數(shù)據(jù)緩沖區(qū)(一個字節(jié)類型的數(shù)組)byte[]buf=newbyte[256];存放從客戶端接收的請求信息。4.創(chuàng)立一個DatagramPacketpacket=newDatagramPacket(buf,256);用來從socket接收數(shù)據(jù),它只需要兩個參數(shù)。5.效勞器阻塞socket.receive(packet);在客戶的請求數(shù)據(jù)報到來之前一直等待。86.從到來的包中得到地址和端口號

InetAddressaddress=packet.getAddress();intport=packet.getPort();7.將數(shù)據(jù)送入緩沖區(qū)

或來自文件、或鍵盤輸入8.建立報文包,用來從socket上發(fā)送信息

packet=newDatagramPacket(buf,buf.length,address,port);9.發(fā)送數(shù)據(jù)包

socket.send(packet);

10.關閉socket

socket.close();9接收端接收數(shù)據(jù)報的標準步驟:1.定義數(shù)據(jù)成員intport;InetAddressaddress;DatagramSocketsocket;DatagramPacketpacket;byte[]sendBuf=newbyte[256];2.建立socket

socket=newDatagramSocket();103.向效勞器發(fā)出請求報文address=InetAddress.getByName(args[0]);port=parseInt(args[1]);packet=newDatagramPacket(sendBuf,256,address,port);socket.send(packet);這個數(shù)據(jù)報本身帶有客戶端的信息4.客戶機等待應答packet=newDatagramPacket(sendBuf,256);socket.receive(packet);如果沒有到就一直等待,因此實用程序要設置時間限度5.處理接收到的數(shù)據(jù)Stringreceived=newString(packet.getData());System.out.println(received);113.4數(shù)據(jù)報通信 ——組播通信DatagramSocket只允許數(shù)據(jù)報發(fā)往一個目的地址。類包中提供了類MulticastSocket,允許將數(shù)據(jù)報以播送的方式發(fā)送到某個端口的所有客戶。類MulticastSocket是在客戶端使用,監(jiān)聽效勞器播送來的數(shù)據(jù);而效勞器端仍然使用DatagramSocket來發(fā)送數(shù)據(jù),只是發(fā)送的數(shù)據(jù)報的目的地址有所變化。12類MulticastSocket:從DatagramSocket繼承而來構造方法publicMulticastSocket()publicMulticastSocket(int

port):在指定的端口通信這兩個方法都將拋出例外IOException,程序中需要捕獲處理。主要方法publicvoidjoinGroup(InetAddress

mcastaddr):參加一個播送組publicvoidleaveGroup(InetAddress

mcastaddr):離開一個播送組publicvoidsetTimeToLive(int

ttl):指定數(shù)據(jù)報離開時間publicvoidsend(DatagramPacket

p,byte

ttl):在指定的時間內將數(shù)據(jù)報發(fā)送出去這四個方法都將拋出例外IOException,程序中需要捕獲處理。繼承DatagramSocket的方法publicvoidreceive(DatagramPacket

p):接收數(shù)據(jù)publicvoidsend(DatagramPacket

p):發(fā)送數(shù)據(jù)publicvoidconnect(InetAddress

address,int

port):與指定的機器通信publicvoiddisconnect():關閉指定的連接publicvoidclose():關閉Socket13MulticastSocketsocket=newMulticastSocket(4446);InetAddressaddress=InetAddress.getByName("");socket.joinGroup(address);…//receivedatagramsocket.leaveGroup(address);socket.close();InetAddressgroup=InetAddress.getByName("");DatagramPacketpacket=newDatagramPacket(buf,buf.length,group,4446);socket.send(packet);客戶端效勞器端14播送組的IP地址是一類特殊的IP地址,它們沒有分配給網(wǎng)上的硬件資源使用,而是專門保存下來作為播送通信使用的〔就像是專門用來描述本機IP一樣〕。這一類地址的范圍是從到,其中地址又被保存不能被一般應用程序所使用。當前,播送通信只能在應用程序中使用,不能在Applet中使用。15許多防火墻和路由器可以配置為不允許UDP數(shù)據(jù)報進入。因此,如果想在這種環(huán)境下提供UDP網(wǎng)絡效勞,就需要請求系統(tǒng)管理員重新配置防火墻和路由器,以允許UDP數(shù)據(jù)報進入。163.5UDP網(wǎng)絡編程案例1〕網(wǎng)絡編程UDP協(xié)議的“Hello,world”程序17import.*;importjava.io.*;public

classUDPClient{public

static

voidmain(String[]args)throwsSocketException,IOException{Stringh="hello,world";byte[]b=h.getBytes();InetAddressiip=InetAddress.getByName("localhost");DatagramSocketds=newDatagramSocket();DatagramPacketdp=newDatagramPacket(b,b.length,iip,3334);ds.send(dp);}}182〕UDP協(xié)議聊天程序importjava.awt.*;import.*;importjava.io.*;import.*;class

myClient

extendsFrame{DatagramSocketds1;DatagramPacketdp1=null;DatagramSocketds2;DatagramPacketdp2=null;InetAddressiip;byte[]b;Panelp1,p2;Buttonbs;TextAreat1;TextFieldt2,t3;Labell1,l2;ttct;19myClient(Stringss)throwsSocketException,IOException{super(ss);p1=newPanel();p2=newPanel();t1=newTextArea();t2=newTextField("那你就去吧,別讓妖精迷住!",34);l1=newLabel("昵稱");l2=newLabel("消息");t3=newTextField("悟空");bs=newButton("發(fā)送");bs.addActionListener(newbss());addWindowListener(newww());setLayout(newFlowLayout());p1.setLayout(newBorderLayout());p1.add(t1);add(p1);p2.setLayout(newFlowLayout());p2.add(l1);p2.add(t3);p2.add(l2);p2.add(t2);p2.add(bs);add(p2);setBounds(100,100,460,260);setVisible(true);ds1=newDatagramSocket();20ds2=newDatagramSocket(3335);iip=InetAddress.getByName("localhost");t=newttc(this);t.start();}classbssimplementsActionListener{public

voidactionPerformed(ActionEvente){try{dp1=newDatagramPacket((t3.getText().trim()+":"+t2.getText().trim()).getBytes(),((t3.getText()+t2.getText().trim()).getBytes()).length,iip,3334);ds1.send(dp1);t1.append(t3.getText().trim()+":"+t2.getText()+"\n");}catch(IOExceptione1){}}}classwwextendsWindowAdapter{public

voidwindowClosing(WindowEventee){System.exit(0);}}21public

static

voidmain(String[]args)throwsIOException,SocketException{newmyClient("Client");}}classttcextendsThread{myClientmc=null;ttc(myClientmc){this.mc=mc;}public

voidrun(){while(true){try{mc.b=new

byte[1024];mc.dp2=new);mc.ds2.receive(mc.dp2);mc.t1.append(newString(mc.b).trim()+"\n");}catch(IOExceptiongg){}}}}223〕組播地址通信import.*;importjava.io.*;importjava.util.*;publicclassMultiCast{ privateMulticastSocketms=null; privateInetAddressip=null; privateScannersc=null; byte[]b=newbyte[4096]; privateDatagramPacketind=newDatagramPacket(b,b.length); privateDatagramPacketoutd=null; publicvoidinit()throwsIOException { try { ms=newMulticastSocket(30000); ip=InetAddress.getByName(""); ms.joinGroup(ip); ms.setLoopbackMode(false); outd=newDatagramPacket(newbyte[0],0,ip,30000); newmyThread().start(); sc=newScanner(System.in);

23while(sc.hasNextLine()) { byte[]buff=sc.nextLine().getBytes(); outd.setData(buff); ms.send(outd); } } finally { ms.close(); }

} classmyThreadextendsThread { publicvoidrun() { try { while(true) { ms.receive(ind); ("消息:"+newString(b,0,b.length)); } }

24 catch(IOExceptionex) { try { if(ms!=null) { ms.leaveGroup(ip); ms.close(); } System.exit(1); } catch(IOExceptionss) {

} } } }

publicstaticvoidmain(String[]args)throwsIOException { newMultiCast().init(); }}254〕組播地址聊天程序import.*;importjava.awt.*;importjava.io.*;import.*;public

class

multiCast

extendsFrame{Panelp1,p2;Buttonbs;TextAreat1;TextFieldt2,t3;Labell1,l2;privateMulticastSocketms=null;privateInetAddressip=null;byte[]b=new

byte[1024];privateDatagramPacketind=newDatagramPacket(b,b.length);privateDatagramPacketoutd=null;26publicmultiCast(Stringss)throwsIOException{super(ss);p1=newPanel();p2=newPanel();t1=newTextArea();t2=newTextField("大師兄,我去捉妖精吧!",34);t3=newTextField("八戒");bs=newButton("發(fā)送");l1=newLabel("昵稱");l2=newLabel("消息");bs.addActionListener(newbss());addWindowListener(newww());setLayout(newFlowLayout());p1.add(t1);add(p1

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論