如何在客户端和服务器之间建立多个 IO 流?
我正在 Java 中创建一个客户端/服务器对,目前仅支持通过围绕服务器和客户端 IO 流的 PrintWriter 和 BufferedReaders 进行隔行文本通信。
我想实现一个使用 Image[Input/Output]Stream 以设定的时间间隔将 BufferedImage 从服务器发送到客户端的函数。
问题是我希望在单独的线程中发送/接收 BufferedImage,以便客户端/服务器仍然可以发送/接收文本命令。
我可以创建多个流或套接字吗?如果是这样,这是最好的方法吗?
I'm creating a client/server pair in Java that, for now, only supports interlaced text communication via PrintWriters and BufferedReaders wrapped around both server and client's IO streams.
I would like to implement a function that uses Image[Input/Output]Stream to send a BufferedImage from the server to the client at a set interval.
The problem is that I want the BufferedImages to be sent/received in separate threads so that the client/server can still send/receive text commands.
Can I create multiple streams or sockets? If so, is that the best way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用单个套接字实现此目的的一种方法是通过连接到套接字的单个字节流复用各个流,一个很好的实现是 BEEP 。
One way to accomplish this with a single socket is multiplexing the individual streams over a single bytestream connected to the socket, a good implementation of this is BEEP.
是的,当然您可以根据需要创建任意数量的线程和套接字。请小心:不要忘记关闭套接字并控制线程创建过程:太多线程不会提高您的性能,甚至可能导致您的系统停止运行。
也许你应该使用线程池。但这取决于您的应用程序。查看
java.util.concurrency
包。如果您有更具体的问题,请随时提出。
Yes, sure you can create as many threads and sockets as you need. Just be careful: do not forget to close sockets and keep process of threads creation under control: to many threads do not improve your performance and may even cause your system to halt.
Probably you should use thread pool. But it depends on your application. Take a look on
java.util.concurrency
package.If you have more specific questions do not hesitate to ask them.
多路复用流应维护多个缓冲区。
应该通过多路复用流为读取器提供它自己的缓冲区。多路复用流应在写入操作期间增大每个缓冲区,并在读取操作期间缩小所需的缓冲区。
单个倒带缓冲区更难管理,因为读取器需要有状态,但通常更具可扩展性(即使不是高性能)。
使用的具体连接协议是实现细节。网络套接字只是缓冲区,可用于实现多路复用流。在这种情况下,网络成为瓶颈。
A multiplexing stream should maintain multiple buffers.
A reader should be given it's own buffer by the multiplexing stream. The multiplexing stream should grow every buffer during a write operation, and shrink the desired buffer during a read operation.
A single rewind buffer is harder to manage, since the readers need to be stateful, but is generally more scalable, if not performant.
The specific connection protocol used is an implementation detail. Network sockets are just buffers, and can be used to implement a multiplexing stream. The network becomes the bottleneck in this case.