Avatar of gplana
gplana
Flag for Spain asked on

Java DatagramSocket problem

I have an application which sends a DatagramPacket to another by using a DatagramSocket. The sending application has a loop which gets a data from user (2 bytes) and then sends it to the receiving application. The receiving application has a loop which gets data from the DatagramSocket and prints it to console.

First packet is sended ok and showed to console by the receiver. However, after that, when receiver repeats the loop, the instruction dg.receive(p); doesn't seems to keep wainting until new data is received.

This is the code on the receiver:

                  dg = new DatagramSocket(port);
                  while(true)
                  {
                        p = new DatagramPacket(buf,2);
                        dg.receive(p);
                        buf = p.getData();
                        nvia = buf[0];
                        if ((nvia <= nvies) && (nvia>0))
                              vies[nvia-1] = buf[1];
                        
                        // Mostro l'estat de les vies
                        System.out.println("\n\n\n");
                        System.out.println("Estat de les vies");
                        System.out.println("-----------------");
                        for (nvia=1; nvia<=nvies; nvia++)
                              System.out.println("Via " + nvia + ":" + vies[nvia-1]);
                  }
Java

Avatar of undefined
Last Comment
gplana

8/22/2022 - Mon
gplana

ASKER
The error message that appears on the client is:
No buffer space available (maximum connections reached?): Cannot bind

The server seems to enter to an infinite looping without waiting for data to arrive.
Tomas Helgi Johannsson

        Hi!

Take a look at this example on how to read/write a DataGramPacket through DataGramSocket.
http://www.java2s.com/Code/Java/Network-Protocol/ReadandwritewithDatagramPacket.htm

Remember to close the socket after sending/receiving the data to allow other connections to
be established.

Regards,
    Tomas Helgi
gplana

ASKER
Thank you. Just a question: if I want a loop which sends a message on every iteration on the loop,  should I close and open again or can I maintain the datagramsocket open for all messages and close at the end of the program ?
Your help has saved me hundreds of hours of internet surfing.
fblack61
ASKER CERTIFIED SOLUTION
Tomas Helgi Johannsson

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
gplana

ASKER
Thank you very much.