Java Socket 客户端模式
我的java应用程序必须将消息(多线程)发送到套接字服务器。该应用程序每秒可以发送大约 100-200 条消息。
我想知道哪种方法更好?
- 打开单个客户端套接字并通过此套接字从所有线程发送消息。 缺点:必须处理连接失败时的重连逻辑,重连时可能会丢失很多消息。线程安全,阻塞?
- 为每个线程创建一个新的客户端套接字连接,并在发送后关闭它。 缺点:即使我关闭套接字,端口也会等到 TIME_WAIT 周期。
哪一个是更好的实用方法?
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 ?
- 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 ?? - 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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议3:
每个线程打开一个套接字,并重用线程(例如通过线程池)。然后在线程内处理重新连接,或者只是正确处理它并创建新的。这样您可以避免阻塞和同步问题
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
每秒 100-200 条消息并不算多。我不会每次都重新连接,因为这很昂贵。如果您重新使用连接,速度会快得多。
如果您担心丢失消息,可以发送一批消息或一次发送一条消息,然后等待服务器确认已收到消息。您仍然可以通过这种方式每秒发送数千条消息。
100-200 messages per second isn't that much. 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.