学习过程中有参考Redisson和RocketMq对于netty的使用
一、服务端
1、启动类
@Autowired
private WebsocketProperties properties;
@Autowired
private WebSocketChannelInitializer webSocketChannelInitializer;
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
public void start() throws InterruptedException {
prepareExecutorService();
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childOption(ChannelOption.TCP_NODELAY, true)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(webSocketChannelInitializer);
Channel channel = serverBootstrap.bind(properties.getPort()).sync().channel();
log.info("Websocket server run at port: " + properties.getPort());
channel.closeFuture().sync();
}
2、实现ChannelInitializer(暂时未考虑ssl)
@Autowired
private WebsocketProperties properties;
@Autowired
private HttpRequestHandler httpRequestHandler;
@Autowired
private TextWebSocketFrameHandler textWebSocketFrameHandler;
@Override
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
SslContext sslContext = configureSslContext();
if (sslContext != null) {
pipeline.addLast(sslContext.newHandler(channel.alloc()));
}
pipeline
.addLast(new WebSocketIdleStateHandler())
.addLast(new HttpServerCodec())
.addLast(new HttpObjectAggregator(65536))
.addLast(httpRequestHandler)
.addLast(PingWebSocketFrameHandler.INSTANCE)
.addLast(textWebSocketFrameHandler)
.addLast(CloseWebSocketFrameHandler.INSTANCE);
}
配置的空闲检测为读15秒钟,客户端心跳请求

本文介绍了如何基于Netty实现WebSocket协议的服务端和客户端,详细讲解了服务端的启动、ChannelInitializer配置以及客户端的连接与心跳发送、断线重连功能。通过使用SimpleChannelInboundHandler进行帧类型判断,确保了二进制数据的正确处理。同时,文章提到了在Spring应用中启动Netty服务的注意事项,包括ByteBuf的引用计数管理和业务处理的线程池设计。
最低0.47元/天 解锁文章
2049

被折叠的 条评论
为什么被折叠?



