使用Netty框架实现一个简单的CS结构的网络程序处理tcp半包问题粘包、拆包完整代码
以下是使用Netty框架实现一个简单的C/S结构的网络程序处理tcp半包问题的完整代码:
服务端代码:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
public class Server {
public static void main(String[] args) throws Exception {
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.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 LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2));
pipeline.addLast(new LengthFieldPrepender(2));
pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
byte[] bytes = new byte[msg.readableBytes()];
msg.readBytes(bytes);
String message = new String(bytes, "UTF-8");
System.out.println("Received message from client: " + message);
}
});
}
});
ChannelFuture future = bootstrap.bind(8888).sync();
System.out.println("Server started on port 8888...");
future.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
客户端代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 8888);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("Enter message to send to server: ");
String message = reader.readLine();
out.println(message);
String response = in.readLine();
System.out.println("Received response from server: " + response);
}
}
}
在这个示例中,服务端使用了LengthFieldBasedFrameDecoder和LengthFieldPrepender来解决tcp半包问题。LengthFieldBasedFrameDecoder会自动处理粘包和拆包,并将每个完整的消息分配给SimpleChannelInboundHandler处理。客户端通过Socket连接到服务端,使用PrintWriter将消息发送给服务端,然后通过BufferedReader读取服务端的响应
原文地址: https://www.cveoy.top/t/topic/cEXZ 著作权归作者所有。请勿转载和采集!