Ducksauce88
Ducksauce88

Reputation: 650

Should I close my socket after every successful message handle?

I am writing a program that has a Java Server/Client socket. There will be many messages sent back and forth, and in some situations, sending a message to the server and waiting for a period of time until the server has sent back a "execute" message.

Here is what I have planned:

I have started to build the program to have this setup above, and once a message is received on the server, the servers performs actions based upon the input and then sends back a message to the client. I have had problems in the past where messages were not sent or received properly, so my question is:

Upvotes: 5

Views: 7783

Answers (3)

user207421
user207421

Reputation: 310913

You should certainly keep TCP connections open for as long as possible, but be prepared to create a new one on failure. You will need to use read timeouts at both ends to detect those.

Upvotes: 4

Jef Vrijhoeven
Jef Vrijhoeven

Reputation: 102

Whether or not you close the socket after a message depends on the protocol that you use between the server and the clients. Probably you define this yourself. What is probably more important, is that you are able to serve multiple clients in parallel. Therefore, you need to start a separate thread for every client that requests a connection. Personally, I made some applications with socket communication. To prevent keeping resources for too long when they are not used, but also not closing and reopening constantly when a connection is heavily used, I added a connection supervisor. This is yet another thread, that does is started when a connection is opened, and just performs a countdown from a predefined value (e.g. countdown from 60, decreqsing the value every second for a supervision time of 1 minute). When the counter reaches zero, order to close the socket, and terminate that particular thread. When a socket is open, and receives a new message, then reset the supervision counter, so the socket will remain open, as long as the time between messages is less than 1 minute.

Upvotes: -2

paulsm4
paulsm4

Reputation: 121649

Q: Should I open a new socket each connection, or keep it around and re-use it for subsequent connections?

A: "It depends".

I would encourage you to "Keep it Simple" and simply open new socket as needed ... until you find that you need otherwise.

By all means: keep the socket open for as long as you reasonably expect a "dialog" between your client and server. Don't force the client to establish a new connection if he's likely to want to talk again reasonably quickly.

Finally, take a look at these links regarding "Connection Pooling":

Upvotes: 0

Related Questions