简体   繁体   English

Java Socket客户端模式

[英]Java Socket Client pattern

My java application has to send messages(multithreaded) to a socket server. 我的java应用程序必须将消息(多线程)发送到套接字服务器。 The application can send around 100-200 messages a second. 该应用程序每秒可以发送大约100-200条消息。

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. 缺点:即使关闭套接字,端口也会等到TIME_WAIT周期。

Which is a better practical approach ? 哪种更实用?

I would propose 3. : Open an socket per thread, and reuse threads (for example via thread pool). 我建议3.:每个线程打开一个套接字,并重用线程(例如通过线程池)。 Then handle reconnection inside thread, or just dispose it properly and create new one. 然后处理线程内部的重新连接,或者只是正确处理它并创建新的线程。 This way you can avoid blocking and synchronisation issues 这样您就可以避免阻塞和同步问题

100-200 messages per second isn't that much. 每秒100-200条消息并不多。 I wouldn't re-connect every time as this is expensive. 我不会每次都重新连接,因为这很昂贵。 If you re-use your connection, it will be much faster. 如果您重新使用连接,它会快得多。

If you are worried about losing messages, you can send a batch of messages or one at a time and wait for a confirmation from the server they have been received. 如果您担心丢失消息,可以一次发送一批消息,然后等待收到服务器的确认。 You can still send thousands of messages per second this way. 您仍然可以通过这种方式每秒发送数千封邮件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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