Search code examples
javasocketssocket.iostream-socket-client

Java Socket Client pattern


My java application has to send messages(multithreaded) to a socket server. The application can send around 100-200 messages a second.

I want to know which is a better approach to do this ?

  1. Open a single client socket and send the message from all threads though this one socket. Disadvantages: Have to handle the reconnection logic on connection failure,may lose many messages when reconnection is in process.Thread safety, blocking ??
  2. Create a new client socket connection for each thread and close it after sending. Disadvantages: Even though I close the socket, the ports will wait till the TIME_WAIT period.

Which is a better practical approach ?


Solution

  • I would propose 3. : Open an socket per thread, and reuse threads (for example via thread pool). Then handle reconnection inside thread, or just dispose it properly and create new one. This way you can avoid blocking and synchronisation issues