What is the best practice in socket programming? Do I close every time or leave it open?

I did not find a clear answer to this question.

I have a client / server application in Java 7. The server and client are on separate computers. The client has a short (1 line of 10 characters) command to issue to the server, and the server responds (120 characters). This will be repeated every X seconds - where X is the speed in the configuration file. It can be as short as 1 second for Integer.MAX_VALUE seconds.

Each time I created a client / server application, the philosophy created the connection, did the business, closed the connection and then did something else with the data. It seems like everything should be done, especially when using an attempt with resource programming.

What is a hiccup with the output of a socket hanging there for X seconds? Is it really best to close and restart, or is it better to use a socket to connect and just send a command every X seconds?

+4
source share
2 answers

I think the answer depends on the number of customers you expect.

If you will never have many client connections open, I would say disconnecting the connection and calling it good, especially if there is a problem with the delay - even on local networks, I saw that it takes several milliseconds to initialize. If you expect hundreds or thousands of clients to connect and do this, however, I would connect again. As others said, leaving non-blocking sockets open often means that you have a thread left running, which can take up several megabytes of stack space for each thread. Do this a few thousand times and you will have a big problem on most machines.

Another problem is port space. Just because the TCP / IP stack gives us 65,535 shared ports, this does not mean that they are all usable - in fact, most local firewalls will prohibit most of the use, so even if you have enough memory to run thousands of simultaneous streams, you can very likely exit ports if you leave a lot of connections at the same time.

+3
source

IMHO the client must open, do it and then close.

on the server ... On UNIX, the process of answering a call (each call) is usually called; however, Windows typically creates a new thread for each incoming call.

0
source

Source: https://habr.com/ru/post/1491966/


All Articles