我可以使用两个不同的线程在同一个套接字上读写吗?
我正在为作业写一些小东西,我必须管理主机之间的 TCP 连接。我的愿景最初是两个 TCP 连接,一个传入,一个传出,以及一个非常复杂的协议来管理这些连接的创建和销毁。
那么,这是一个我希望可行的更简单的替代方案。一个插座,易连接,易破坏。一个线程将数据写入该套接字上的流,一个线程从同一套接字上的流读取数据。我对阻塞没有任何问题,所以我不需要使用 nio 来做任何事情。
我能让这件事发生吗?
I'm writing a little thing for an assignment, and I have to manage TCP connections between hosts. My vision was originally two TCP connections, one incoming, one outgoing, and a really elaborate protocol to manage the creation and destruction of these connections.
So then, here is a simpler alternative that I hope works. One socket, easy to connect, easy to destroy. One thread writing data to the stream on that socket, one thread reading from the stream on that same socket. I have no problem with blocking, so I don't need to use nio for anything.
Can I make this happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
TCP套接字是一个全双工流,您可以从多个线程读取和写入它。这样做是否是一个好主意是一个完全不同的问题。
TCP socket is a full-duplex stream, you can read from and write to it from multiple threads. Whether doing so is a good idea is a totally different question.
如果您只有编写器线程和一个读取器线程,则可能会生成更清晰、更简单的代码。
希望通过该套接字进行通信的其他线程将通过某个队列将请求传递给编写器线程。类似地,读取器将通过队列将传入消息分派到适当的线程。
该技术通常用于用户界面。
It would probably result in clearer and simpler code if you had only writer thread and only one reader thread.
Other threads wishing to communicate via that socket would pass requests to the writer thread via some queue. Similarly, the reader would dispatch incoming messages to the appropriate threads via queue.
This technique is commonly used for user interfaces.
据我所知,套接字是线程安全的。仅当从一个线程对套接字调用 close() 时才应该小心。第二个可以挂在某些阻塞函数上或无限选择。
As far as I know sockets are thread safe. You should only be careful when you call close() on socket from one thread. Second one could hang on some blocking function or select infinitely.
是的,你可以这样做。您可以使用 ServerSocket,另一个线程通过 Socket。您可以通过 google 搜索大量 EchoServer/EchoClient 示例来开始使用。
Yes you can do that. You can have 1 thread start a server using ServerSocket, and another thread connecting to this Server via Socket. You can google for plenty of examples for EchoServer/EchoClient to get started.