问题三:netty客户端发送完消息就断开(无法接收数据)
问题描述:我需要完成的流程是netty客户端和服务端一直连接着,我测试一调接口,就进到客户端的动态代理的invoke里,完成一系列操作。而我原代码是一发送完消息客户端直接主动断开了,单单留服务端在运行。
当时解决完没保存原码,实现原理我也还没有很了解,如果有人了解的话,可以给我讲解一下重点代码是哪里吗,我就直接放我修改后的代码好了。
客户端代码
public class NettyClient {
private static Logger logger = Logger.getLogger(NettyClient.class);
static EventLoopGroup group = null;
static Bootstrap client = null;
public static ChannelFuture future = null;
public static void run(){
group = new NioEventLoopGroup();
client = new Bootstrap();
client.group(group);
client.channel(NioSocketChannel.class);
client.option(ChannelOption.SO_KEEPALIVE,true);
client.handler(new ClientInitalizer());
try {
future = client.connect("localhost", 8080).sync();
future.channel();
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
public static void main(String[] args) {
}
}
public class ClientInitalizer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
/***
maxFrameLength - 发送的数据包最大的长度
lengthFieldOffset - 长度域偏移量,长度域位于整个数据包字节数组中的下标
lengthFieldLength - 长度域自己的字节数长度
lengthAdjustment – 长度域的偏移量矫正。 如果长度域的值,还包含了其他域(如长度域自身)长度,那么值为:包长 - 长度域的值 – 长度域偏移 – 长度域长
initialBytesToStrip – 丢弃的起始字节数。丢弃处于有效数据前面的字节数量。
***/
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024,2,4,-4,6));
ch.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));
ch.pipeline().addLast(new ClientHandler());
ch.pipeline().addLast(new StringEncoder());
}
}
服务端代码
public class NettyServer {
private static Logger logger = Logger.getLogger(NettyServer.class);
static EventLoopGroup bossLoopGroup;
static EventLoopGroup workLoopGroup;
static ServerBootstrap server;
static {
bossLoopGroup = new NioEventLoopGroup();
workLoopGroup = new NioEventLoopGroup();
server = new ServerBootstrap();
server.group(bossLoopGroup,workLoopGroup);
server.channel(NioServerSocketChannel.class);
server.option(ChannelOption.SO_BACKLOG,128);
server.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
server.option(ChannelOption.SO_KEEPALIVE,true);
server.childHandler(new ServerInitalizer());
}
public static void run(int port){
try {
ChannelFuture future = server.bind(new InetSocketAddress(port)).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
} finally {
bossLoopGroup.shutdownGracefully();
workLoopGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
}
}
服务端的ServerInitalizer类我就不放的,和客户端基本一样。