简体   繁体   中英

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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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