Netty与Websocket使用protobuf实现聊天系统

服务端:Netty
序列化数据协议:protobuf
前端通讯:WebSocket

前端:

    
    

服务端:

      ChannelPipeline pipeline = ch.pipeline();
       pipeline.addLast(new ChunkedWriteHandler());
       pipeline.addLast(new ChunkedWriteHandler());
       pipeline.addLast(new WebSocketServerCompressionHandler());
       pipeline.addLast(new  WebSocketServerProtocolHandler ("/xxx"
        ,null,true));
      // 协议包解码
       pipeline.addLast(new MessageToMessageDecoder() {
             @Override
              protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List objs) throws Exception {
              ByteBuf buf = ((BinaryWebSocketFrame) frame).content();
                   objs.add(buf);
                   buf.retain();
               }
       });
  // 协议包编码
   pipeline.addLast(new MessageToMessageEncoder() {
        @Override
         protected void encode(ChannelHandlerContext ctx, MessageLiteOrBuilder msg, List out) throws Exception {
             ByteBuf result = null;
                                    if (msg instanceof MessageLite) {
                                        result = wrappedBuffer(((MessageLite) msg).toByteArray());
                                    }
                                    if (msg instanceof MessageLite.Builder) {
                                        result = wrappedBuffer(((MessageLite.Builder) msg).build().toByteArray());
                                    }

                                    
                                    WebSocketFrame frame = new BinaryWebSocketFrame(result);
                                    out.add(frame);
                                }
                            });
  pipeline.addLast(new ProtobufDecoder(MsgPOJO.msg
  .getDefaultInstance()));
  pipeline.addLast(new ServerFrameHandler());
public class ServerFrameHandler extends SimpleChannelInboundHandler {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MsgPOJO.msg msg) throws Exception {
        System.out.println(msg.getUserId());
        System.out.println(msg.getMessage());
        System.out.println(msg.getGroupId());
        MsgPOJO.msg build = MsgPOJO.msg.newBuilder().setType(2).setMessage("你好,客户端").setGroupId("002").setUserId("u80876").build();
        ctx.channel().writeAndFlush(build);
    }
}
 
 
image.png

你可能感兴趣的:(Netty与Websocket使用protobuf实现聊天系统)