java-如何知道SocketChannel的另一端是否关闭?

时间:2018-10-04 11:03:56

标签: java sockets tcp socketchannel

我看到另一个答案说read()将在对等方关闭时返回-1,而write()将抛出IOException

尽管我的程序让我感到困惑:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(0));

SocketChannel socket = SocketChannel.open(serverSocketChannel.getLocalAddress());
SocketChannel peer = serverSocketChannel.accept();

peer.close();

int read;
int write;

read = socket.read(ByteBuffer.allocate(1));
System.out.println("read = " + read);
write = socket.write(ByteBuffer.allocate(1));
System.out.println("write = " + write);

它输出:

read = -1
write = 1

read()方法返回-1,但是write()不会引发异常。


然后我尝试更改write()read()的顺序:

write = socket.write(ByteBuffer.allocate(1));
System.out.println("write = " + write);
read = socket.read(ByteBuffer.allocate(1));
System.out.println("read = " + read);

输出:

write = 1
Exception in thread "main" java.io.IOException: An established connection was aborted by the software in your host machine
    at sun.nio.ch.SocketDispatcher.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:43)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
    at sun.nio.ch.IOUtil.read(IOUtil.java:197)
    at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
    at Core.main(Core.java:76)

这让我更加困惑:write()仍然没有抛出IOException,但是有read()抛出。


我删除了write(),然后再添加一个read()

write = socket.write(ByteBuffer.allocate(1));
System.out.println("write = " + write);
write = socket.write(ByteBuffer.allocate(1));
System.out.println("write = " + write);

输出看起来更奇怪:

write = 1
Exception in thread "main" java.io.IOException: An established connection 
was aborted by the software in your host machine
    at sun.nio.ch.SocketDispatcher.write0(Native Method)
    at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:51)
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
    at sun.nio.ch.IOUtil.write(IOUtil.java:65)
    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:471)
    at Core.main(Core.java:76)

第一个write()不会引发任何异常,但是第二个会引发任何异常。


我不知道结果是否未定义,因为我找不到关于文档中同级物的任何信息。 预先感谢!

0 个答案:

没有答案