File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Distributed Java and the fly likes Socket connection best practice Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Distributed Java
Bookmark "Socket connection best practice" Watch "Socket connection best practice" New topic

Socket connection best practice

Steven Bruton

Joined: Mar 07, 2011
Posts: 13
I'm writing a client / server application which depends on socket connections to communicate.

What I'd like to know is should I keep the same socket connection open and continually reuse it until the client closes the connection or should I be closing the connection after a task is complete and create a new socket connection to service the next task.
Mir Mohammed Easin

Joined: Mar 07, 2011
Posts: 4
The best practice in socket programming is that to use same socket connection for a connected client. Once the client operation is done and no need to proceed with that client then close the socket connection for that client. Eventually the next client will be connected and Server will proceed with the new one. But if your Server is handing multiple client then you need to create a Thread for the clients which will handle every clients seperately so that no socket connection will be miss or lost.

William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13036
Also, be very very very sure that sockets get closed when you are finished. A socket ties up operating system resources which will eventually be exhausted if you don't, causing mysterious system crashes.

Steven Bruton

Joined: Mar 07, 2011
Posts: 13
Cheers for the input guys, much appreciated.
I agree. Here's the link:
subject: Socket connection best practice
jQuery in Action, 3rd edition