简体   繁体   English

使用NIO的Java套接字通信

[英]Java socket communication using NIO

Currently, our application uses socket input and output streams for communication. 当前,我们的应用程序使用套接字输入和输出流进行通信。 In the concrete example, it reads from a console input stream and writes to a socket output stream. 在具体示例中,它从控制台输入流读取并写入套接字输出流。 If the socket input is closed from the outside, but the writing is blocking, the output stream can not be closed causing to hang. 如果套接字输入是从外部关闭的,但是写入受阻,则无法关闭输出流,导致挂起。

Hence I thought to use some polling in a loop where the (console) input stream is polled regularly to detect whether it is closed and hence close the output stream. 因此,我想在一个循环中使用一些轮询,在该循环中定期轮询(控制台)输入流以检测其是否关闭,从而关闭输出流。

According to this article it looks like I have to take SocketChannel s instead of inputstream and outputstream. 根据本文看来,我必须采用SocketChannel而不是inputstream和outputstream。 Are inputstream and outputstream decoupled so I can first try it with SocketChannel for the inputstream and leave the outputstream code as is? 输入流和输出流是否解耦,所以我可以先对输入流使用SocketChannel进行尝试,然后将输出流代码保持原样?

SocketChannel has pretty different usage model instead of Sockets. SocketChannel的使用模式与Sockets完全不同。 But you may of course open SocketChannel and send data using write(...) methods. 但是,您当然可以打开SocketChannel并使用write(...)方法发送数据。

SocketChannel allows non-blocking network calls (so it is very scalable), and it is more cheap in opening connections (less CPU overhead). SocketChannel允许无阻塞的网络调用(因此它具有很高的可伸缩性),并且在打开连接时更便宜(较少的CPU开销)。

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

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