netty客户可以';使用DelimiterBasedFrameDecoder和decode时,无法从服务器接收响应
客户: 服务器:netty客户可以';使用DelimiterBasedFrameDecoder和decode时,无法从服务器接收响应,netty,Netty,客户: 服务器: public class ClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("Start"); ctx.writeAndFlush(Unpooled.copiedBuffer
public class ClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Start");
ctx.writeAndFlush(Unpooled.copiedBuffer("aa$_".getBytes()));
ctx.writeAndFlush(Unpooled.copiedBuffer("bbbb$_".getBytes()));
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
String response = (String)msg;
System.out.println("Server feedback: "+ response);
}finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
如果我直接通过客户端发送消息,请使用cf.channel()
如下:
public class ServerHandler extends ChannelInboundHandlerAdapter{
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String str = (String)msg;
System.out.println("Client: "+str);
// String response = "Server";
// response = response+"$_";
ctx.writeAndFlush(Unpooled.copiedBuffer("Server!!!!$_".getBytes()));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
客户端和服务器均未接收任何数据
但是,如果我注释掉客户端中decode和DelimiterBasedFrameDecoder的代码(clientHandler需要使用Bytebuf),客户端和服务器都可以接收消息,尽管服务器接收的消息已经解包(只有客户端有问题)
如果我通过channelActive以clientHandler发送消息:
Server feedback: Server!!!!$_Server!!!!$_
它很好用
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Start");
ctx.writeAndFlush(Unpooled.copiedBuffer("aa$_".getBytes()));
ctx.writeAndFlush(Unpooled.copiedBuffer("bbbb$_".getBytes()));
}
在clientHandler中使用cf.channel()
和ctx
发送消息有什么区别
Netty 4.1.15尝试打印writeAndFlush在未来返回的异常,查看如何快速打印此异常。您可能在建立连接之前发送数据,请尝试在连接方法之后添加一个
.sync()
。谢谢,我确实忘记在连接方法之后添加.syn()
。请尝试打印writeAndFlush在其未来返回的异常,查看如何快速打印此异常。您可能在建立连接之前发送数据,请尝试在连接方法之后添加.sync()
。谢谢,我确实忘记在连接方法之后添加.syn()
。
cf.channel().writeAndFlush(Unpooled.copiedBuffer("aa$_".getBytes()));
cf.channel().writeAndFlush(Unpooled.copiedBuffer("bbbb$_".getBytes()));
Server feedback: Server!!!!$_Server!!!!$_
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Start");
ctx.writeAndFlush(Unpooled.copiedBuffer("aa$_".getBytes()));
ctx.writeAndFlush(Unpooled.copiedBuffer("bbbb$_".getBytes()));
}
Server feedback: Server!!!!
Server feedback: Server!!!!