netty做了一个微信聊天室服务端,客户端调试时候有时候能收到消息,有时候收不到。

服务端debug模式时候大部分都能收到消息。但是关闭debug时候就很大几率收不到消息。摘出来服务端的关键代码。我觉得是异步消息发送的原因,这个要怎么处理?protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

    Channel inChannel = ctx.channel();

    if(!channelList.contains(inChannel)){
        channelList.add(inChannel);
    }

    if(msg instanceof TextWebSocketFrame) {
        System.out.println(">>>>>>>>>>>>>>>处理文本信息");
        userList = this.addUserinList(inChannel, msg);
        for (Channel channel : channelList) {
            channel.writeAndFlush((TextWebSocketFrame)msg);
        }
    }else if(msg instanceof BinaryWebSocketFrame){
        System.out.println(">>>>>>>>>>>>>>>处理图片信息");
        BinaryWebSocketFrame binaryWebSocketFrame = new BinaryWebSocketFrame(Unpooled.buffer().writeBytes("xxx".getBytes()));
        inChannel.writeAndFlush(binaryWebSocketFrame);
    }else {

        System.out.println("服务端收到的信息类型是其他类型!");
    }

}

writeAndFlush这个是通道异步刷新消息的吗?客户端是websocket协议。

这个原因也找到了。原因是因为我在workhandle中使用了多线程处理长连接,这样会造成消息发送不及时。处理方法:使用单线程就可以了。
ChannelPipeline p = channel.pipeline();
p.addLast(new HttpServerCodec());//http协议编码器
p.addLast(new ChunkedWriteHandler());//以块的形式来写
p.addLast(new HttpObjectAggregator(1024*1024*1024));//获取请求的最大的长度
p.addLast(new WebSocketServerProtocolHandler("/chat"));//适配 ws://127.0.0.1:6001/chat

    p.addLast("BusinessHandler",businessExise);

最后这一行,这样用就行了。