无法让2个客户端监听一台UDP服务器

时间:2019-12-16 18:17:40

标签: java udp client

我有一个UDP(服务器),它正在从用户接收数据,然后进行一些计算并将新数据发送回去,我可以肯定地说服务器正在从第一个客户端以及第二个客户端接收数据。但只有第一个客户端正在接收数据 这是我在两个客户端中的接收方法

private void receive(){

         try{
            DatagramSocket socket = new DatagramSocket(2390);
            byte[] buffer = new byte[2048];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet);
            String msg = new String(buffer,0,packet.getLength());
            String[] coor = msg.split(" ");
            x = Integer.parseInt(coor[0]);
            y = Integer.parseInt(coor[1]);
            x1 = Integer.parseInt(coor[2]);
            y1 = Integer.parseInt(coor[3]);
            packet.setLength(buffer.length);
            socket.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

第二个客户端尝试使用此接收方法时,出现异常:

java.net.BindException: Address already in use: Cannot bind
    at java.net.DualStackPlainDatagramSocketImpl.socketBind(Native Method)
    at java.net.DualStackPlainDatagramSocketImpl.bind0(Unknown Source)
    at java.net.AbstractPlainDatagramSocketImpl.bind(Unknown Source)
    at java.net.DatagramSocket.bind(Unknown Source)
    at java.net.DatagramSocket.<init>(Unknown Source)
    at java.net.DatagramSocket.<init>(Unknown Source)
    at java.net.DatagramSocket.<init>(Unknown Source)
    at Game.receive(Game.java:73)
    at Game.<init>(Game.java:58)
    at Game.main(Game.java:92)

1 个答案:

答案 0 :(得分:2)

您应该为客户端new DatagramSocket();使用no-arg构造函数

  

no-arg构造函数用于创建绑定到任意端口号的客户端。第二个构造函数用于创建绑定到特定端口号的服务器,因此客户端知道如何连接。

private void receive(){

         try{
            DatagramSocket socket = new DatagramSocket();

            byte[] buffer = new byte[2048];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet);


            String msg = new String(buffer,0,packet.getLength());
            String[] coor = msg.split(" ");
            x = Integer.parseInt(coor[0]);
            y = Integer.parseInt(coor[1]);
            x1 = Integer.parseInt(coor[2]);
            y1 = Integer.parseInt(coor[3]);
            packet.setLength(buffer.length);
            socket.close();
        }catch(Exception e){
            e.printStackTrace();
        }
}

另外,套接字应该只创建一次,所以可能不存在,我认为此receive方法处于这样的循环中……

// here is a good place to init the socket
DatagramSocket socket = new DatagramSocket();
while(true){
    //receive();
    receive(socket); //pass the socket if it is a local

}
相关问题