开发的时候总会遇到一些有趣的问题,Netty发送不了1024byte!已解决!
问题描述
这次主要使用netty建立WebSocket服务端,服务端可以正常收到消息,服务端调用writeAndFlush
客户端无法收到消息
调试
将io.netty日志等级降低到debug
日志打印 Encoding WebSocket Frame opCode=1 length=1074
length超过1024客户端就无法收到消息
服务端收到:{"random":"5926","code":1,"roomId":1}
2021-01-09 00:00:50.214 DEBUG 20316 --- [ntLoopGroup-3-1] i.n.h.c.h.w.WebSocket08FrameEncoder : Encoding WebSocket Frame opCode=1 length=1074
检查依赖
发现io.netty版本不一致,可能会导致冲突!
解决
pom.xml添加以下代码片段
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-bom</artifactId>
<version>4.1.36.Final</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
结果
搞定!关闭浏览器
代码片段1
@Component
@Slf4j
public class WebSocketNettyServer {
private EventLoopGroup parentGroup = new NioEventLoopGroup();
private EventLoopGroup childGroup = new NioEventLoopGroup();
private Channel channel;
public ChannelFuture bing(InetSocketAddress address) {
ChannelFuture channelFuture = null;
try {
ServerBootstrap b = new ServerBootstrap()
.group(parentGroup, childGroup)
.channel(NioServerSocketChannel.class) //非阻塞模式
//子处理器,用于处理wss
.childHandler(new HttpChannelInitializer())
.option(ChannelOption.SO_BACKLOG, 1024)
// 两小时没有数据通信时,TCP自动发送一个活动探测报文
.childOption(ChannelOption.SO_KEEPALIVE, true);
channelFuture = b.bind(address).syncUninterruptibly();
channel = channelFuture.channel();
} catch (Exception e) {
log.error(e.getMessage());
} finally {
if (null != channelFuture && channelFuture.isSuccess()) {
log.info("dnetty server start done. ");
} else {
log.error("netty server start error. ");
}
}
return channelFuture;
}
public void destroy() {
if (null == channel) return;
channel.close();
parentGroup.shutdownGracefully();
childGroup.shutdownGracefully();
}
public Channel getChannel() {
return channel;
}
}
代码片段2
public class HttpChannelInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
// HTTP 服务的解码器
pipeline.addLast("http-codec", new HttpServerCodec());
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
pipeline.addLast("http-chunked", new ChunkedWriteHandler());
pipeline.addLast(new MyChannelHandler());
}
}