结合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 简单栗子

Mina、Netty、Twisted一起学(五):整合protobuf

protobuf是谷歌的Protocol Buffers的简称,用于结构化数据和字节码之间互相转换(序列化、反序列化),一般应用于网络传输,可支持多种编程语言。protobuf如何使用这里不再介绍,本...

MINA、Netty、Twisted一起学(五):整合protobuf

protobuf是谷歌的Protocol Buffers的简称,用于结构化数据和字节码之间互相转换(序列化、反序列化),一般应用于网络传输,可支持多种编程语言。 protobuf如何使用这里不再介绍,...

Netty的protobuf的图书订购服务端开发

Netty的protobuf的图书订购服务端开发 一.Protobuf简介 Google的protobuf在业界非常流行,很多商业项目选择protobuf作为编解码框架。它是一个灵活,高效,结构化...

Netty的Protobuf开发列子

Netty的Protobuf开发列子

Netty Protobuf C# 通信

Java 使用 Netty 与 C# 进行通信

netty学习七:集成protobuf完成单个对象序列化以及在网络上传输

概述本文介绍使用netty集成google的protobuf框架,完成proto JAVA对象的序列化和反序列化。编写proto文件protobuf使用.proto文件来描述对象结构体的信息。 Pe...

Netty5 Protobuf通信 解决半包

本文整合网上资源 给出了完整版本  对于高负载、高并发的网络应用,自己开发nio服务端,难度比较大、稳定性不能保证。于是选择nio框架netty+protobuf。netty对于消息编码和解码、半包读...

【Netty基础】protobuf详解

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

Netty使用protobuf作为通信协议

Netty中使用protobuf 环境准备 下载protoc代码生成器和源码包:http://code.google.com/p/protobuf/downloads/list, pro...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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