Java实战:Netty+SpringBoot打造TCP长连接通讯方案
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
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;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
public class TCPServer {
private int port;
public TCPServer(int port) {
this.port = port;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new TCPServerHandler());
}
});
ChannelFuture f = b.bind(port).sync();
System.out.println("服务器启动,监听端口:" + port);
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
TCPServer server = new TCPServer(8080);
server.run();
}
}
这个示例代码展示了如何使用Netty框架来创建一个基本的TCP长连接服务器。服务器监听8080端口,并使用LengthFieldBasedFrameDecoder
和LengthFieldPrepender
处理帧解码和编码,确保消息边界被正确识别。同时,它展示了如何添加StringDecoder
和StringEncoder
来处理字符串消息,以及如何自定义处理器TCPServerHandler
来处理具体的业务逻辑。这个代码提供了一个简单的模板,可以根据具体需求进行扩展和修改。
评论已关闭