结合Netty与Protobuf小栗子

原创 2015年11月18日 16:30:48

结合Netty与Protobuf

基于上一篇生成protobuf的例子,接下来看看怎么与netty结合做个demo~

如何基于protobuf生成Java类请参考上一篇:
http://blog.csdn.net/drizzt0878/article/details/49890121

1. 编写服务端响应的protobuf文件

package com.nettydemo.protobuf;
option java_package = "com.nettydemo.protobuf";
option java_outer_classname = "MsgSendResponseProto";

message MsgSendResponse {
  required string msgID = 1;
  required string result = 2;
}

2. 编译并生成MsgSendResponseProto.java


3. 实现的需求

客户端 –> sendMsg –> 服务端
服务端(接收消息后) –> sendMsgResponse –> 客户端(接收响应消息)


4. 代码实现

服务端代码实现:(MsgSendResponseProto.java , MsgSendServer.java , MsgSendServerHandler.java)

public class MsgSendServer {

    private static final Logger logger = Logger.getLogger(MsgSendServer.class);

    public static void main(String[] args) throws Exception {
        ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                // 解码用
                pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
                // 构造函数传递要解码成的类型
                pipeline.addLast("protobufDecoder",
                        new ProtobufDecoder(MsgSendProto.MsgSend.getDefaultInstance()));

                // 编码用
                pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                pipeline.addLast("protobufEncoder", new ProtobufEncoder());

                // 业务逻辑处理
                pipeline.addLast("handler", new MsgSendServerHandler());
                return pipeline;
            }

        });

        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);
        bootstrap.bind(new InetSocketAddress(8080));

        logger.info("server start up...");
    }
}

public class MsgSendServerHandler extends SimpleChannelHandler {

    private static final Logger logger = Logger.getLogger(MsgSendServerHandler.class);

    @Override
    public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
        if (e instanceof ChannelStateEvent) {
            logger.info(e.toString());
        }
        super.handleUpstream(ctx, e);
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) {
        // 收到客户端发送的消息,已经解码成了MsgSendProto类型
        final MsgSendProto.MsgSend msgSendProto = (MsgSendProto.MsgSend) e.getMessage();
        System.out.println("receive msg from client: " + msgSendProto);

        // 返回成功接收信息给客户端
        MsgSendResponseProto.MsgSendResponse.Builder builder = MsgSendResponseProto.MsgSendResponse.newBuilder();
        builder.setMsgID(msgSendProto.getMsgID());
        builder.setResult("1");
        e.getChannel().write(builder.build());
    }
}

客户端代码实现:( MsgSendProto.java , MsgSendClient.java , MsgSendClientHandler.java )

public class MsgSendClient {

    public static void main(String[] args) {

        ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();

                // 解码用
                pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
                // 构造函数传递要解码成的类型
                pipeline.addLast("protobufDecoder", new ProtobufDecoder(
                        MsgSendResponseProto.MsgSendResponse.getDefaultInstance()));

                // 编码用
                pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                pipeline.addLast("protobufEncoder", new ProtobufEncoder());

                // 业务逻辑用
                pipeline.addLast("handler", new MsgSendClientHandler());
                return pipeline;
            }

        });

        ChannelFuture connectFuture = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8080));
        // Wait until the connection is made successfully.
        Channel channel = connectFuture.awaitUninterruptibly().getChannel();
        MsgSendClientHandler handler = channel.getPipeline().get(MsgSendClientHandler.class);

        // send msg
        handler.sendMsg2Server();
    }
}

public class MsgSendClientHandler extends SimpleChannelUpstreamHandler {

    private volatile Channel channel;

    private static final Logger logger = Logger.getLogger(MsgSendClientHandler.class);

    @Override
    public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        channel = e.getChannel();
        super.channelOpen(ctx, e);
    }

    @Override
    public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
        if (e instanceof ChannelStateEvent) {
            logger.info(e.toString());
        }
        super.handleUpstream(ctx, e);
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) {
        // 收到服务端返回的消息,已经解码成了MsgSendResponse类型
        final MsgSendResponseProto.MsgSendResponse response = (MsgSendResponseProto.MsgSendResponse) e
                .getMessage();
        System.out.println("receive response from server: msgID=" + response.getMsgID() + ", resultCode="
                + response.getResult());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        logger.warn("Unexpected exception from downstream.", e.getCause());
        e.getChannel().close();
    }

    public void sendMsg2Server() {
        // 先进行序列化
        MsgSendProto.MsgSend.Builder builder = MsgSendProto.MsgSend.newBuilder();
        builder.setMsgID("20151101");
        builder.setPhone("13100000000");
        builder.setDoneTime(System.currentTimeMillis());
        builder.setEnterpriseID(1);
        builder.setEnterpriseName("enterprise");
        builder.setResult(1);
        builder.setChannelID(1);
        builder.setCarrier(1);
        builder.setBusyType(1);
        builder.setSize(5);
        builder.setUnit(1);
        channel.write(builder.build());
    }
}

运行结果

客户端

这里写图片描述


服务端

这里写图片描述

Netty5 简单栗子

Netty5 简单栗子

netty+protobuf入门案例

  • 2014年04月14日 08:04
  • 1.65MB
  • 下载

netty4 tcp与protobuf3的整合使用。

netty是一个非常棒的NIO框架就不介绍了。protobuf是google提供的一个开源序列化框架,也是一个非常棒的东西。这里不介绍这两个框架了,想要了解的朋友网上一搜一大把。 本文主要介...
  • KokJuis
  • KokJuis
  • 2017年06月02日 16:56
  • 1279

netty+protobuf入门案例.

  • 2014年06月28日 13:31
  • 1.63MB
  • 下载

Netty发送protoBuf格式数据

  • 2017年09月15日 14:54
  • 4.68MB
  • 下载

【Netty基础】protobuf详解

前言我在上篇博文中简单介绍了一下protobuf,由于protobuf是Netty默认的序列化协议,再说它的性能也很高,接下来就详细的说一下protobuf协议!引入Netty为什么要提供编解码框架作...

采用netty与protobuf进行文件传输

  • 2017年07月15日 08:26
  • 759KB
  • 下载

Netty5 Protobuf通信 解决半包

本文整合网上资源 给出了完整版本  对于高负载、高并发的网络应用,自己开发nio服务端,难度比较大、稳定性不能保证。于是选择nio框架netty+protobuf。netty对于消息编码和解码、半包读...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:结合Netty与Protobuf小栗子
举报原因:
原因补充:

(最多只允许输入30个字)