Java 如何在Netty channelRead()上读写
我正在运行Netty,我需要从客户端读取一些消息。 然后我需要在服务器上执行一些操作,然后向客户端发送响应。 也许客户端需要再次应答服务器。 我认为所有这些都必须发生在同一条线上。 如何在Netty服务器中执行此操作? 我正在使用Telnet测试下面的代码,但我无法从服务器获得响应。 如果我对第一个块(readmessageblock)进行注释,那么我开始在Telnet控制台中接收响应Java 如何在Netty channelRead()上读写,java,sockets,netty,Java,Sockets,Netty,我正在运行Netty,我需要从客户端读取一些消息。 然后我需要在服务器上执行一些操作,然后向客户端发送响应。 也许客户端需要再次应答服务器。 我认为所有这些都必须发生在同一条线上。 如何在Netty服务器中执行此操作? 我正在使用Telnet测试下面的代码,但我无法从服务器获得响应。 如果我对第一个块(readmessageblock)进行注释,那么我开始在Telnet控制台中接收响应 @Override public void channelRead(ChannelHandlerContext
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
// Read the message sent from client.
try{
ByteBuf in = (ByteBuf) msg;
try {
while (in.isReadable()) { // (1)
System.out.print((char) in.readByte());
System.out.flush();
}
}
catch(Exception e){
System.out.println("---------------- Reading Exception ----------------");
e.printStackTrace();
}finally{
//ReferenceCountUtil.release(msg);
}
// treat the received message
if(msg.equals("teste")){
// do Something...
}
//Answer to the client
try {
ctx.write(msg); // (1)
ctx.flush(); // (2)
}
catch(Exception e){
System.out.println("---------------- Writing Exception ----------------");
e.printStackTrace();
}
}
finally {
//ReferenceCountUtil.release(msg); // (2)
}
}
在while循环之后:
while(in.isReadable()){…}
,消息ByteBuf不再可读,因此不会通过ctx.write(msg)