Java UDP communication: Java datagram socket class and datagram packet class

Datagram packet class

Datagram socket class

Example 1

public static void main(String[] args)
{
    DatagramSocket ds=null;
    DatagramPacket dpSend=null;
    InetAddress ia=InetAddress.getByName("127.0.0.1");
    int port=3021;
}
try
{
    ds=new DatagramSocket();
    for(int i=0;i<5;i++)
    {
        byte[] data=("我是 UDP 客户端"+i).getBytes();
        dpSend=new DatagramPacket(data,data.length,ia,port);
        ds.send(dpSend);
        Thread.sleep(1000);
    }
    ds.close();
}
catch(IOException | InterruptedException e)
{
    // TODO 自动生成的 catch 块
    e.printStackTrace();
}   
public static void main(String[] args)
{
    DatagramSocket ds=null;
    DatagramPacket dpReceive=null;
    int port=3021;
}
try
{
    ds=new DatagramSocket(port);
    System.out.println("UDP服务器已启动。。。");
    byte[] b=new byte[1024];
    while(ds.isClosed()==false)
    {
        dpReceive=new DatagramPacket(b,b.length);
        try
        {
            ds.receive(dpReceive);
            byte[] Data=dpReceive.getData();
            int len=Data.length;
            System.out.println("UDP客户端发送的内容是:" + new String(Data,len).trim());
            System.out.println("UDP客户端IP:" + dpReceive.getAddress());
            System.out.println("UDP客户端端口:" + dpReceive.getPort());
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
    }
    catch(SocketException e1)
    {
        // TODO 自动生成的 catch 块
        e1.printStackTrace();
    }
}
UDP服务器已启动。。。
UDP客户端发送的内容是:我是UDP客户端0
UDP客户端IP:/127.0.0.1
UDP客户端端口:53472
UDP客户端发送的内容是:我是UDP客户端1
UDP客户端IP:/127.0.0.1
UDP客户端端口:53472
UDP客户端发送的内容是:我是UDP客户端2
UDP客户端IP:/127.0.0.1
UDP客户端端口:53472
UDP客户端发送的内容是:我是UDP客户端3
UDP客户端IP:/127.0.0.1
UDP客户端端口:53472
UDP客户端发送的内容是:我是UDP客户端4
UDP客户端IP:/127.0.0.1
UDP客户端端口:53472
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>