[英]Illegal blocking mode exception while attempting to read from socket
I am pretty new to Java and am trying to code a sender-channel-receiver setup, where the channel represents a transmission medium and introduces errors to the packets. 我对Java还是很陌生,正在尝试编写一个sender-channel-receiver设置的代码,该通道代表传输介质,并向数据包引入错误。 So the channel is connected to the sender and the receiver using server socket channels.
因此,该通道使用服务器套接字通道连接到发送方和接收方。 Most of it is fine, but when I attempt to read the object
Packet
within the channel, it throws IllegalBlockingModeException
. 大部分都很好,但是当我尝试在通道内读取对象
Packet
,它会抛出IllegalBlockingModeException
。 The sender throws what seems to be a corresponding IO exception, "An existing connection was forcibly closed by the remote host". 发送方抛出似乎是相应的IO异常的消息:“现有连接已被远程主机强行关闭”。 The code in the
Channel
program is as follows (some parts excluded for simplicity): Channel
程序中的代码如下(为简单起见,排除了某些部分):
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
keyIterator.remove();
if (key.isAcceptable()) {
SocketChannel sc = ((ServerSocketChannel) key.channel()).accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
}
if (key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
sc.configureBlocking(false);
Packet packet = readPacket(sc);
sc.close();
// do things with the packet...
where readPacket
is defined as follows: readPacket
的定义如下:
private static Packet readPacket(SocketChannel sc) throws IOException,
ClassNotFoundException {
ObjectInputStream in = new
ObjectInputStream(sc.socket().getInputStream());
Packet packet = (Packet) in.readObject();
return packet;
}
is someone able to please explain what is throwing the exception and how to rectify it? 有人能够解释引发异常的原因以及如何纠正该异常吗?
Streams are blocking. 流正在阻塞。 You cannot use them in non-blocking mode.
您不能在非阻止模式下使用它们。 See the Javadoc.
请参阅Javadoc。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.