开发者

Java socket communication using NIO

开发者 https://www.devze.com 2023-02-18 18:21 出处:网络
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 socke开发者_JAVA百科t output stream. If

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 socke开发者_JAVA百科t 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 SocketChannels instead of inputstream and 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 has pretty different usage model instead of Sockets. But you may of course open SocketChannel and send data using write(...) methods.

SocketChannel allows non-blocking network calls (so it is very scalable), and it is more cheap in opening connections (less CPU overhead).

0

精彩评论

暂无评论...
验证码 换一张
取 消