gpt4 book ai didi

java - 如何通过SocketChannel以非阻塞方式读写序列化对象?

转载 作者:行者123 更新时间:2023-12-01 21:34:46 27 4
gpt4 key购买 nike

我目前正在尝试通过 NIO SocketChannel 读取和写入序列化对象。此 SocketChannel 处于非阻塞模式。我似乎无法找到正确的方法来做到这一点而不破坏流,破坏流头等......

这是我当前的写入方法

private void writeData(SelectionKey key) throws IOException {
Packet outPacket = null;
synchronized (pendingPacketQue) {
for (Packet packet : pendingPacketQue) {
if (packet.getChannel().keyFor(selector).equals(key)) {
outPacket = packet;
break;
}
}
}
if (outPacket == null) {
Logger.writeException("Couldn't find out bound packet in list.", LogType.SERVER);
return;
}
SocketChannel connection = (SocketChannel) outPacket.getChannel();
ObjectOutputStream outStream = new ObjectOutputStream(connection.socket().getOutputStream());
outStream.writeObject(outPacket);
outStream.flush();
outStream.close();
connection.keyFor(selector).interestOps(SelectionKey.OP_READ);
}

这是我当前的阅读方法

private void readData(SelectionKey key) throws IOException, ClassNotFoundException {
SocketChannel connection = (SocketChannel) key.channel();
buffer.clear();
int byteCount;
try {
byteCount = connection.read(buffer);
} catch (IOException e) {
Logger.writeException("Connenction terminated.", LogType.SERVER);
connection.close();
key.cancel();
return;
}
if (byteCount == -1) {
Logger.writeException("Connection error. Terminating connection.", LogType.SERVER);
key.channel().close();
key.cancel();
return;
}
Engine.getInstance().getPacketProcessor().processData(connection, buffer.array(), byteCount);
}

public void processData(SocketChannel connection, byte[] data, int count)
throws IOException, ClassNotFoundException {
ByteArrayInputStream byteStream = new ByteArrayInputStream(data);
ObjectInputStream inStream = new ObjectInputStream(byteStream);
addToQue(inStream.readObject());
inStream.close();
}

如果您有任何疑问,请随时提问。谢谢!

最佳答案

您不必在一次读取中读取整个对象。

你也不能这样写作。您不能使用 SocketChannel 的套接字流在非阻塞模式下。你应该有一个IllegalBlockingModeException在发件人中。

因此,当您一开始就不可能编写任何内容时,很难看出您如何可能达到损坏的流 header 等地步。

无论如何,我强烈建议您不要尝试这样做。太难了。您需要在对象之前发送对象的大小,以便您知道何时读完所有内容,发出多次读取并保存结果,直到拥有所有内容,运行等等。使用 java.net.Socket和普通对象直接输入和输出流。

关于java - 如何通过SocketChannel以非阻塞方式读写序列化对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37040600/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com