UDP通信
DatagramSocket類 用于創建收發UDP數據包的Socket對象
構造函數
DatagramSocket() //用于發送方,系統分配端口號
DatagramSocket(int port) //用于接收方
DatagramSocket(int port,InetAddress laddr)
//udp在多個Ip地址的計算機,用于發送接收
方法
close() //關閉對象,釋放資源
send(DatagramPacket p) //發送數據包
receive(DatagramPacket p) //接收數據包
DatagramPacket類 創建UDP數據包
構造函數
public DatagramPacket(byte[] buf,int length)
//內存緩存區,大小 接收數據對象
public Datagrampacket(byte[] buf,int length,
InetAddress address,int port)
//內存緩存區,大小,ip,端口 發送數據對象
getInetAddress
getPort
getData 返回buf
getLength 返回length
InetAddress類
getByName() 靜態方法
//根據字符串格式,返回一個相應的實例對象
getHostAddress()
//返回.分格的IP
2 import java.net.*;
3 public class UdpSend {
4 //發送方
5 /**
6 * @param args
7 */
8 public static void main(String[] args) throws Exception{
9 // TODO Auto-generated method stub
10 DatagramSocket ds = new DatagramSocket();//創建socket發送對象,發送端口號由系統分配。
11 String strInfo="hello china 中國";//定義要發送的字符串
12 DatagramPacket dp=new DatagramPacket(strInfo.getBytes(),strInfo.getBytes().length,
13 InetAddress.getByName("192.168.1.111"),3333); //構建數據包
14 ds.send(dp);//發送數據包
15 ds.close();
16
17 }
18
19 }
20
2 import java.net.*;
3 public class UdpRev {
4
5 public static void main(String[] args) throws Exception{
6 //創建socket接收對象
7 byte[] buff=new byte[1024];
8 DatagramSocket ds= new DatagramSocket(3333);
9 DatagramPacket p= new DatagramPacket(buff,1024);
10 ds.receive(p);
11 System.out.println("content:\t"+new String(buff,0,p.getLength())
12 +"\nfrom\t"+p.getAddress().getHostAddress()+":"+p.getPort());
13 ds.close();
14 }
15
16 }
posted on 2010-12-29 12:30 杰點 閱讀(140) 評論(0) 編輯 收藏 所屬分類: JAVA