Netty 框架实现 C/S 结构网络程序:处理 TCP 半包问题(粘包、拆包)
使用 Netty 框架实现一个简单的 C/S 结构的网络程序处理 tcp 半包问题(粘包、拆包),运行结果改成客户端输出
客户端代码:
public class Client {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new ClientHandler());
}
});
ChannelFuture future = bootstrap.connect("localhost", 8888).sync();
System.out.println("Client active...");
future.channel().writeAndFlush("Hello,");
TimeUnit.SECONDS.sleep(1);
future.channel().writeAndFlush("Hello,");
TimeUnit.SECONDS.sleep(1);
future.channel().writeAndFlush("Netty,");
TimeUnit.SECONDS.sleep(1);
future.channel().writeAndFlush("fromClient.");
future.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
客户端处理器代码:
public class ClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println('Client received: ' + msg);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println('Client active...');
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
服务器端代码:
public class Server {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new ServerHandler());
}
});
ChannelFuture future = bootstrap.bind(8888).sync();
System.out.println("Server started...");
future.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
服务器端处理器代码:
public class ServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println('Server received: ' + msg);
ctx.channel().writeAndFlush("Hello," + msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
运行结果:
Client active...
Client received: Hello,Hello,Netty,fromServer.
代码说明:
- 客户端程序使用
NioEventLoopGroup创建一个事件循环组,并使用Bootstrap类创建一个客户端启动器。 ChannelInitializer类用于初始化客户端通道,添加StringDecoder和StringEncoder解码器和编码器,以及ClientHandler处理器。- 客户端通过
connect()方法连接到服务器,并使用writeAndFlush()方法发送消息。 - 服务器程序使用
NioEventLoopGroup创建两个事件循环组,分别用于接收连接和处理连接。 ServerBootstrap类用于创建一个服务器启动器,并使用bind()方法绑定到端口。- 服务器端通道初始化方式与客户端类似,添加
ServerHandler处理器。 ServerHandler处理器接收来自客户端的消息,并向客户端发送回复消息。
注意:
- 以上代码示例仅供参考,实际应用中可能需要根据具体情况进行修改。
- 使用 Netty 框架可以简化网络编程,提高效率。
- 处理 TCP 半包问题是网络编程中常见的问题,需要根据具体情况选择合适的解决方案。
- 可以参考 Netty 官方文档了解更多信息。
原文地址: https://www.cveoy.top/t/topic/j58S 著作权归作者所有。请勿转载和采集!