UDP数据发送

import java.net.*;
class netDemo
{
    public static void main(String[] args)throws Exception
    {
        System.out.println("发送数据。。。。。");
        DatagramSocket ds=new DatagramSocket();
        String str="哥来了";
        byte[] buf=str.getBytes();
        DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),1000);
        ds.send(dp);
        ds.close();
    }    
}
import java.net.*;
class netDemo
{
    public static void main(String[] args)throws Exception
    {
        System.out.println("接收数据。。。。。");
        DatagramSocket ds=new DatagramSocket(1000);
    
        byte[] buf=new byte[1024];
        DatagramPacket dp=new DatagramPacket(buf,buf.length);
        ds.receive(dp);
        String ip=dp.getAddress().getHostAddress();
        int port=dp.getPort();
        String text=new String(dp.getData(),0,dp.getLength());
        ds.close();
        System.out.println(ip+""+port+""+text);
    }
    public static void Method1()
    {
        
    }
}

 

 

posted on 2012-11-19 23:26  蝌蚪的精神  阅读(174)  评论(0编辑  收藏  举报

导航