各项目之间通常使用二进制进行通讯,占用带宽小、处理速度快~

感谢netty作者Trustin Lee。让netty天生支持protocol buffer。

本实例使用netty4+protobuf-2.5.0。在win7下运行。而且如果已经安装jdk和maven。

1、下载并解压protoc-2.5.0-win32.zip和protobuf-2.5.0.zip

2、到protobuf-2.5.0.zip安装文件夹protobuf-2.5.0\java下,运行maven命令:mvn package jar:jar,将生成target\protobuf-java-2.5.0.jar

3、定义proto文件test.proto:

package domain;



option java_package = "com.server.domain";



message TestPro {

  required string test = 1;

}

4、将第2部的jar包复制到java文件存放文件夹下,然后执行以下命令,生成java文件:

protoc-2.5.0-win32.zip安装文件夹\protoc.exe --java_out=java文件存放文件夹 proto定义文件文件夹\test.proto

5、将生成的protobuf-java-2.5.0.jar和netty4的jar包放到项目的classpath中,并将第4部生成的java文件放到项目的对应路径下。

6、编写Server端代码

1)、编写handler类:

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.SimpleChannelInboundHandler;



public class ServerHandler extends SimpleChannelInboundHandler<Test.TestPro> {

@Override

public void channelRead0(ChannelHandlerContext ctx, Test.TestPro msg) throws Exception {

System.out.println("server:" + "channelRead:" + msg.getTest());



Test.TestPro.Builder builder = Test.TestPro.newBuilder();

builder.setTest("Received your message !");

ctx.writeAndFlush(builder.build());

}

}

2)、注冊服务,绑定port:

import io.netty.bootstrap.ServerBootstrap;

import io.netty.channel.Channel;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelInitializer;

import io.netty.channel.ChannelOption;

import io.netty.channel.EventLoopGroup;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.nio.NioServerSocketChannel;

import io.netty.handler.codec.protobuf.ProtobufDecoder;

import io.netty.handler.codec.protobuf.ProtobufEncoder;



public class Server {



public static void main(String[] args) {

EventLoopGroup bossEventLoopGroup = new NioEventLoopGroup();

EventLoopGroup workerEventLoopGroup = new NioEventLoopGroup();

try {

ServerBootstrap serverBootstrap = new ServerBootstrap();

serverBootstrap.group(bossEventLoopGroup, workerEventLoopGroup);

serverBootstrap.channel(NioServerSocketChannel.class);

serverBootstrap.childHandler(new ChannelInitializer<Channel>() {

@Override

protected void initChannel(Channel ch) throws Exception {

ch.pipeline().addLast("encoder", new ProtobufEncoder());

ch.pipeline().addLast("decoder", new ProtobufDecoder(Test.TestPro.getDefaultInstance()));

ch.pipeline().addLast("handler", new ServerHandler());

};

});

serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();

channelFuture.channel().closeFuture().sync();

} catch (Exception e) {

e.printStackTrace();

} finally {

bossEventLoopGroup.shutdownGracefully();

workerEventLoopGroup.shutdownGracefully();

}

}

}

7、编写Client端代码

1)、定义Client端的handler类:

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.SimpleChannelInboundHandler;



public class ClientHandler extends SimpleChannelInboundHandler<Test.TestPro> {



@Override

protected void channelRead0(ChannelHandlerContext ctx, Test.TestPro msg) throws Exception {

System.out.println("client:" + "channelRead:" + msg.getTest());

}

}

2)、建立Client端到Server端的连接

import java.io.BufferedReader;

import java.io.InputStreamReader;



import io.netty.bootstrap.Bootstrap;

import io.netty.channel.Channel;

import io.netty.channel.ChannelInitializer;

import io.netty.channel.EventLoopGroup;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.nio.NioSocketChannel;

import io.netty.handler.codec.protobuf.ProtobufDecoder;

import io.netty.handler.codec.protobuf.ProtobufEncoder;

import io.netty.handler.codec.string.StringDecoder;

import io.netty.handler.codec.string.StringEncoder;



public class Client {



public static void main(String[] args) {

EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

try {

Bootstrap bootstrap = new Bootstrap();

bootstrap.group(eventLoopGroup);

bootstrap.channel(NioSocketChannel.class);

bootstrap.handler(new ChannelInitializer<Channel>() {

@Override

protected void initChannel(Channel ch) throws Exception {

ch.pipeline().addLast("encoder", new ProtobufEncoder());

ch.pipeline().addLast("decoder", new ProtobufDecoder(Test.TestPro.getDefaultInstance()));

ch.pipeline().addLast("handler", new ClientHandler());

};

});



Channel ch = bootstrap.connect("127.0.0.1", 8888).sync().channel();



// 控制台输入

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

for (;;) {

String line = in.readLine();

if (line == null || "".equals(line)) {

continue;

}

Test.TestPro.Builder builder = Test.TestPro.newBuilder();

builder.setTest(line);

ch.writeAndFlush(builder.build());

}

} catch (Exception e) {

e.printStackTrace();

} finally {

eventLoopGroup.shutdownGracefully();

}

}

}

新手教程,欢迎拍砖。

推荐其它參考教程:protocol与netty结合的资料http://blog.csdn.net/goldenfish1919/article/details/6719276

netty4与protocol buffer结合简易教程的更多相关文章

  1. Protocol Buffer学习教程之类库应用(四)

    Protocol Buffer学习教程之类库应用(四) 此教程是通过一个简单的示例,给C++开发者介绍一下如何使用protocol buffers编程,主要包括以下几部分: 定义一个.proto文件 ...

  2. Protocol Buffer学习教程之编译器与类文件(三)

    Protocol Buffer学习教程之编译器与类文件(三) 1. 概述 在前面两篇中,介绍了Protobuf的基本概念.应用场景.与protobuf的语法等.在此篇中将介绍如何自己编译protobu ...

  3. 从零开始山寨Caffe·伍:Protocol Buffer简易指南

    你为Class外访问private对象而苦恼嘛?你为设计序列化格式而头疼嘛? ——欢迎体验Google Protocol Buffer 面向对象之封装性 历史遗留问题 面向对象中最矛盾的一个特性,就是 ...

  4. Protocol Buffer学习教程之语法手册(二)

    1.说明 此向导介绍如何使用protocol buffer language创建一个自己的protocolbuffer文件,包括语法与如何通过“.proto”文件生成数据访问的类,此处只介绍proto ...

  5. Protocol Buffer学习教程之开篇概述(一)

    1. Protocol Buffer是什么 Protocol Buffer是google旗下的产品,用于序列化与反序列化数据结构,但是比xml更小.更快.更简单,而且能跨语言.跨平台.你可以把你的数据 ...

  6. Google Protocol Buffer 的使用和原理[转]

    本文转自: http://www.ibm.com/developerworks/cn/linux/l-cn-gpb/ Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构 ...

  7. Emacs简易教程

    Emacs简易教程阅读: 命令: $emacs 进入之后,输入: C-h t 这里,C-h表示按住[Ctrl]键的同时按h ####### 20090620 *退出: 输入“C-x C-c” *撤销: ...

  8. protocol buffer使用简介

    之前在工作中用到了protocol buffer(此处简称PB)(主要对数据进行序列化与反序列化,方便网络传输中的编解码),之后发现这是一个好东西,在此稍微记录下该工具如何使用,方便以后查阅 官网地址 ...

  9. [翻译]Protocol Buffer 基础: C++

    目录 Protocol Buffer Basics: C++ 为什么使用 Protocol Buffers 在哪可以找到示例代码 定义你的协议格式 编译你的 Protocol Buffers Prot ...

随机推荐

  1. laravel socialite微信登录注意

    在token没有过期之前,重新走登录流程时会跳过callback,即不再重新登录,除了删除了客户端的token

  2. fabric的安装

    https://blog.csdn.net/lepton126/article/details/79148027

  3. 1434:【例题2】Best Cow Fences

    1434:[例题2]Best Cow Fences 时间限制: 1000 ms         内存限制: 65536 KB提交数: 263     通过数: 146 [题目描述] 给定一个长度为n的 ...

  4. ERROR 1133 (42000): Can't find any matching row in the user table

    环境:操作系统:Redhat 7.5 x86-64 数据库版本MySQL 5.7.25 现象:ERROR 1133 (42000): Can't find any matching row in th ...

  5. 使用Java(Jedis)链接redis报java.net.ConnectException: Connection refused: connect的错误

    redis环境:centos6 java代码运行环境:windows 第一种情况:未开启redis服务. redis-server /myredis/redis.conf (写你的redis配置文件的 ...

  6. centos6 磁盘与文件系统管理

    一.磁盘管理 磁盘构成 1.圆形磁盘 2.磁盘读取头 3.机械手臂 4.主轴马达 运作原理 数据存储在具有磁性物质的圆形磁盘上,读写操作主要是通过机械手臂上的磁盘读取头来达成,实际运作时,主轴马达让磁 ...

  7. buf.keys()

    buf.keys() 返回:{Iterator} 创建并返回一个包含 Buffer 键名(索引)的迭代器. const buf = Buffer.from('buffer'); for (var ke ...

  8. LeetCode(47)Permutations II

    题目 Given a collection of numbers that might contain duplicates, return all possible unique permutati ...

  9. Final Battle #1 K题 Fire game

    Description Fat brother and Maze are playing a kind of special (hentai) game on an N*M board (N rows ...

  10. 多光源 MultipleLight

    使用2个Pass增加光照效果: 第一个Pass是基础光源,一般是第一个平行光:Tags{"LightMode" = "ForwardBase"} 第二个光源是增 ...