现在有两个客户端,任何一个客户端单独连接netty服务器时,都可以正常发送消息。但是出现了以下问题:一个客户端连接netty服务器时,可以正常发送消息,第二个客户端可以连接netty服务器,但是不能正常发送消息。
@Component
public class SocketInitializer extends ChannelInitializer<SocketChannel> {
@Resource
private NettyServiceHandler nettyServiceHandler;
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new LineBasedFrameDecoder(2048));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
// 添加上自己的处理器
pipeline.addLast(nettyServiceHandler);
}
}
server.netty.NettyServiceHandler is not a @Sharable handler, so can't be added or removed multiple times.
意思是不能nettyServiceHandler不是一个@Sharable handler,所以不能被多个socketChannel添加。所以只有第一个客户端可以正常发送消息,之后的客户端无法正常发送消息。
将NettyServiceHandler的Bean使用@ChannelHandler.Sharable标注
@Component
@ChannelHandler.Sharable
public class NettyServiceHandler extends SimpleChannelInboundHandler<String> {
......
......
}
或者将
pipeline.addLast(nettyServiceHandler);
修改为
pipeline.addLast(new NettyServiceHandler());
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。