杰点

hello java

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

 

 1 //创建基于的UDP发送方
 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 

 1 //基于UDP协议的接收方
 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 杰点 阅读(141) 评论(0)  编辑  收藏 所属分类: JAVA


只有注册用户登录后才能发表评论。


网站导航:
 
<2025年7月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

导航

统计

留言簿

文章分类

文章档案

搜索

最新评论