1
votes

I want to send and receive datagrampacket from same port. Same socket should be used to send packets and receive packets. If i send it then it can not receive incoming packets at the same time. How to synch send and receive packets from single port?

1
Are you meaning UDP datagrams? - robermann
Yes UDP datagram. I want to send and receive voip packets simultaneously from single port. - kaushik parmar
Use two threads, one for send, one for receive. No synch required. - Martin James
I am getting Socket Already in Use error if i use same socket in send and receive. Let me try this with single socket connection. Thanks - kaushik parmar
you are implementing a complex networking system. Use at least two ports in different threads. If you want to reuse them, remember the .close method - robermann

1 Answers

0
votes

You could try something as the following:

    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);