gpt4 book ai didi

java - AsynchronousSocketChannel 一次性写入/读取所有消息

转载 作者:行者123 更新时间:2023-12-02 05:54:01 25 4
gpt4 key购买 nike

尊重,

我尝试使用新的Java NIO2在客户端和服务器端创建异步SocketChannel并进行通信,但问题是我发送到服务器上套接字的所有消息,套接字都将其读取为一条消息。这是代码:

我创建用于写入和读取数据的处理程序:

读取处理程序:

public class ReadHandler implements CompletionHandler<Integer, Msg> {


private AsynchronousSocketChannel _socket;
private SocketHandler _socketHandler;

private ByteBuffer _buffer;

public ReadHandler(SocketHandler socketHandler) {

this._socketHandler = socketHandler;
_buffer = ByteBuffer.allocate(100);

this._socket = this._socketHandler.getSocket();
this._socket.read(_buffer, null, this);
}

@Override
public void completed(Integer result, Msg attachment) {

System.out.println("readdddd " + result);

String message = new String(_buffer.array());
System.out.println("mess:" + message);

}

@Override
public void failed(Throwable exc, Msg attachment) {
System.out.println(exc.getMessage());
}

}

客户端写入处理程序

public class ClientWriteHandler implements CompletionHandler<Integer, Msg> {

private AsynchronousSocketChannel _socket;
private ClientSocket _clientHandler;

private ByteBuffer _buffer;

public ClientWriteHandler(ClientSocket clientHandler) {


this._clientHandler = clientHandler;
_buffer = ByteBuffer.allocate(2048);
this._socket = this._clientHandler.getSocket();
}

@Override
public void completed(Integer result, Msg attachment) {

System.out.println("write " + result);
_buffer.clear();
}

@Override
public void failed(Throwable exc, Msg attachment) {
System.out.println(exc.getMessage());
}

public void write(String data) {
_buffer = ByteBuffer.allocate(2048);
this._socket.write(_buffer.wrap(data.getBytes()), new Msg(), this);

}

}

然后我调用 write 方法 2 次

socket = AsynchronousSocketChannel.open();
socket.connect(new InetSocketAddress("localhost", port)).get();
writeHandler = new ClientWriteHandler(this);
writeHandler.write("hellooo server :)");
writeHandler.write("hellooo server again :)");

我尝试在 ByteBuffer 上使用clear()函数但没有效果。有什么建议吗?

最佳答案

WritePendingException 抛出不是因为缓冲区已满。它被抛出是因为写入尚未完成但另一个开始写入。

关于java - AsynchronousSocketChannel 一次性写入/读取所有消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23270240/

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