Java – what is the best practice for socket programming – do I turn it off or leave it open every time?

I haven't found a definite answer yet

I have a client / server application in Java 7 The server and client are on separate computers The client sends a short (1 line, 10 characters) command to the server, and the server responds (120 strings) This will repeat every x seconds – where x is the rate in the profile This can be as short as 1 second to integer MAX_ Value seconds

Every time I create a client / server application, the idea is to create a connection, perform business, close the connection, and then do anything else with the data This seems to be the right thing to do - especially when trying to program with resources

Hang the socket connection there for x seconds. What kind of hiccup will there be? Is it really a best practice to close and restart, or is it better to keep the socket connected and send commands every x seconds?

Solution

I think the answer depends on the number of customers you expect to have

If you'll never open many client connections, I'll say keep the connection open and call it, especially if latency is a problem - even on the LAN, I've seen that the connection takes a few milliseconds to initialize However, if you want hundreds or thousands of clients to connect and do this, I will reconnect each time As others said, opening a non blocking socket usually means that you have a thread to run, which may take up a few megabytes of stack space on a per thread basis If you do this thousands of times, you will encounter big problems on most machines

Another problem is port space Just because the TCP / IP stack provides us with 65535 total ports does not mean that all ports are available - in fact, most local firewalls prohibit most people from using them, so even if you have enough memory to run thousands of synchronization threads, you can. If you open a large number of connections at the same time, you may run out of ports

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>