我正在编写NIO2服务器,我需要在AsynchronousSocketChannel上进行异步读取操作,每个操作都包括读取一个整数,并进一步读取相同通道的字节数等于这个整数。问题是,当我连续在通道上放置两个或更多CompletionHandler时(因为有多个读取操作的请求),并且第一个处理程序被触发,我在第一个处理程序的complete()
方法中的进一步读取代码不能正常工作,因为当有关于频道的信息时,第二个处理程序会立即被触发。我如何阻止频道直到进一步阅读complete()
完成而没有Future
的事情?我无法使用Future因为我需要将处理程序放到套接字然后传递给其他任务。
for (final Map.Entry<String, AsynchronousSocketChannel> entry : ipSocketTable.entrySet()) {
try {
final AsynchronousSocketChannel outSocket = entry.getValue();
synchronized (outSocket) {
final ByteBuffer buf = ByteBuffer.allocateDirect(9);
outSocket.read(buf, null, new DataServerResponseHandler(buf, outSocket, resultTable, server, entry.getKey()));
}
} catch (Exception e) {
}
}
这是DataServerResponseHandler类:
class DataServerResponseHandler implements CompletionHandler<Integer, Void> {
private ConcurrentHashMap<String, Boolean> resultTable = null;
private AsynchronousSocketChannel channel = null;
private TcpServer server;
private String ip;
private ByteBuffer msg;
public DataServerResponseHandler(ByteBuffer msg, AsynchronousSocketChannel channel,
ConcurrentHashMap<String, Boolean> resultTable, TcpServer server, String ip) {
this.msg = msg;
this.channel = channel;
this.resultTable = resultTable;
this.server = server;
this.ip = ip;
}
@Override
public void completed(Integer result, Void attachment) {
try {
msg.rewind();
int resultCode = msg.get() & 0xff;
int ipOne = msg.get() & 0xff;
int ipTwo = msg.get() & 0xff;
int ipThree = msg.get() & 0xff;
int ipFour = msg.get() & 0xff;
int length = msg.getInt();
msg.rewind();
ByteBuffer buf = ByteBuffer.allocateDirect(length);
channel.read(buf).get();
buf.rewind();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void failed(Throwable exc, Void attachment) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
答案 0 :(得分:0)
此代码有几个问题 第一次读取并不保证它会读取所有剩余的字节,但只要读取至少一个字节就会调用完成处理程序。因此,您必须检查缓冲区的位置并重新调用读取,直到有效负载的标头或长度为9个字节。
if (msg.position() < 9) {
channel.read(msg, null, this);
return;
}
对于第二部分,为了继续异步方法,再次使用完成处理程序运行read。您可以创建一个专门处理有效负载或重用现有负载的新的,您必须记住状态:
switch (state) {
case READ_HEADER:
if (msg.remaining() > 0) {
channel.read(msg, null, this);
return;
}
// do the parsing the IP and length
state = READ_PAYLOAD;
channel.read(payloadBuf, null, this);
break;
case READ_PAYLOAD:
if (payloadBuf.remaining() > 0) {
channel.read(payloadBuf, null, this);
return;
}
payloadBuf.flip();
// get content from payloadBuf
break;
}