简体   繁体   中英

Sockets creation in java client server communication

In a java socket client server program involving client GUI, bearing in mind the below :

  1. Client / server interaction would not be continuous, meaning that an end user might have the GUI left open but would only press buttons / initiate requests every once in a while.

  2. Server would initiate a new thread for each client

  3. All I/O would be via ObjectInput/OutputStream

So based on the above what would be the best approach on the connection/socket creation :

  1. Would it be better to initiate one socket connection per client and keep it alive until the client closes his GUI/session, and treat all I/O within this same connection ?
  2. Or just initiate new socket connection every time a client requests something and close it as soon as the server response is delivered ? (So that one client GUI session might have multiple connections/disconnections to the server)

What are the pros/cons of using one over the other?

Many thanks

For a requests initiated by user "click" i would use the 2nd mode where you open and close connections for every user action separatelly. This will allow you not to keep multiple open connections forever. Keeping connections forever could lead to many problems of resource exhaustion type. If you don't have really important reason to keep open connections eg. that you need to respond to the client with some live messges like a chat, but rather can respond directly after request then it would be much simpler to not keep the connection. It is always better to not keep open idle connections if you don't have to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM