UDP client not available in Java

I am running a simple Java UDP server that collects the client's IP address and port when connected, stores the information in a database.

The client is still listening to the server. The server stops.

Later, the server wants to reuse information about the database in order to contact the client; and since the client is still listening on the same server port, I think the client should receive the message.

I'm new to UDP, please let me know how to achieve my goal. Thanks.

Let me rephrase the question as I have actually tried the ways suggested by Stackoverflow members.

The client can contact the server for a short time, but, say, 10 minutes later the client is unavailable; although the client appears to be willing to listen to the server all the time, but the server is unable to contact the client even if asked multiple times. What could be causing this? please let me know how to handle this.

0


a source to share


2 answers


I think you are a little confused about UDP ( RFC 768 ). I think it would be helpful to look over the UDP protocol to understand the differences between UDP and TCP.



As far as your specific problem is concerned, it's hard to figure out what your exact problem is without some code. There is a Client Server in UDP example available in the sun tutorials.

0


a source


UDP doesn't have a session, so I think it should actually work.

It will look something like this:



// Client:

socket = new DatagramSocket();
DatagramPacket req = new DatagramPacket(data, data.length, serverAddress, serverPort);
socket.send(req);
DatagramPacket resp = new DatagramPacket(new byte[MAX_RESP_SIZE], MAX_RESP_SIZE);
socket.receive(resp);

// Server:

DatagramSocket socket = new DatagramSocket(port);
while (!stopped) {
    DatagramPacket req = new DatagramPacket(new byte[MAX_REQ_SIZE], MAX_REQ_SIZE);
    socket.receive(req);
    saveToDatabase(req.getAddress(), req.getPort());
}
socket.close();

// Then later:

DatagramSocket socket = new DatagramSocket(port);

// retrieve clientAddr and clientPort from database
DatagramPacket resp = new DatagramPacket(data, data.length, clientAddress, clientPort);
socket.send(resp);
socket.close();

      

0


a source







All Articles