netty4與protocol buffer結合簡易教程

來源:互聯網
上載者:User

標籤:space   路徑   .sh   adl   安裝jdk   line   bootstra   keepalive   color   

各項目之間通常使用二進位進行通訊,佔用頻寬小、處理速度快~

感謝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結合簡易教程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.