如何从单个插槽连续发送和接收数据报包。

时间:2014-04-03 08:11:15

标签: java sockets websocket

我想从同一个端口发送和接收datagrampacket。应使用相同的套接字来发送数据包和接收数据包。如果我发送它然后它不能同时接收传入的数据包。如何同步发送和接收来自单个端口的数据包?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下内容:

    DatagramSocket serverSocket = new DatagramSocket(9876);             
    byte[] receiveData = new byte[1024];             
    byte[] sendData = new byte[1024]; 

    //receiving:
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    serverSocket.receive(receivePacket);

    InetAddress callerIPAddress = receivePacket.getAddress();                   
    int callerPort = receivePacket.getPort();

    //sending:  
    sendData = "ciao".getBytes();
    DatagramPacket sendPacket =  new DatagramPacket(sendData, sendData.length, callerIPAddress, callerPort);
    serverSocket.send(sendPacket);