javasocketsserversocket

Use Socket permantently to handle Clientsession or create new one for every request


So i am quite new to Sockets and I have to create a Server-Client-App for school.

I expect a client to request something from the server multiple times during his runtime.

I am uncertain wether I should make a new java.net.Socket for every Request I get (Client opens new socket every time and Java Serversocket accepts) or use a single socket and keep that during the client's runtime.


Solution

  • That strongly depends on how frequently the socket is used.

    E.g. if you know that the client will send a request to the server every 50 milliseconds it would be easier to just keep the socket opened.

    But if you know the client will only request information from the socket every 5 minutes it's probably better to close the connection and create a new one when needed. Same if you don't know when the next request will be created.

    Creating a new Socket on server-side is not very expensive, so it's probably better to just close the connection if it's not used very frequently.

    An exception could be a special socket, that needs authentication or other expensive stuff on creation, but that's probably not the case in a school project.

    So in general: It depends on the usage of the socket, but if you're unsure whether it's used very frequently or not better close it and open it again when needed.