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 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 SocketChannel
s 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).
精彩评论