UDP简单例子

接收端:
1、建立udpsocket服务,给接收端设置端口;
2、定义一个空数据包,用来存储接收到的字节数据,利用数据包对象可以轻松提取字节数据中的不同数据信息;
3、通过socket服务的receive方法将接收到的数据存储到定义好的数据包中;
4、通过数据包对象的特有功能,将这些不同的数据取出,打印在控制台上;
5、关闭资源。
 
class UdpRecevie
{
    public static void main(String[] args) throws Exception
    {
        DatagramSocket ds = new DatagramSocket(10000);
        while(true)
        {
             byte[] buf = new byte[1024];
            DatagramPacket dp = new DatagramPacket(but, but.length);
            ds.receive(dp);//阻塞式方法,没数据就等
            String ip = dp.getAddress().getHostAdress();
            String data = new String(dp.getData(), 0, dp.getLength());
            int port = dp.getPort();
        }
        ds.close();
    }
}

 

使用DatagramSocket进行发送接收,receive(DatagramPacket p)接收,send(DatagramPacket p)发送,
DatagramPacket用于封装数据。
 
发送端:
1、建立udpsocket服务;
2、提供数据,并将数据封装到数据包中;
3、通过socket服务的发送功能,将数据包发送出去;
4、关闭资源。
 
class UdpSend
{
    public static void main(String[] args) throws Exception
    {
        DatagramSocket ds = new DatagramSocket();
        byte[] data = "udp come in".getbytes();
        DatagramPacket dp = new DatagramPacket(data, data.length, InetAddresss.getByName("192.168.1.255"), 1000);
        ds.send(dp);
        ds.close();
    }
}

 

posted @ 2015-07-04 20:46  蜉蝣朝生而暮死  阅读(1335)  评论(0编辑  收藏  举报