netty版本5.0,google protobuf版本2.5.
netty自带的例子io.netty.example.worldclock,就是使用protobuf作为网络协议.
本文实现客户端-服务端之间请求-响应的网络协议,会在worldclock例子上稍作扩展.
首先定义protobuf,对于多种请求的格式,使用Union Type,以下Login,Service分别扩展了Request.
message Request {
extensions 100 to max;
enum Type{
LOGIN=0;
SERVICE=1;
}
required Type type=1;
}
extend Request {
optional Login login = 100;
optional Service service = 101;
}
message Login {
required string user = 1;
required string pswd = 2;
}
message Service {
optional string content = 1;
}
message Response {
optional string result = 1;
}
客户端的主要代码,其他参考worldclock例子.
Login login = Login.newBuilder().setUser("it is user!")
.setPswd("it is pswd!").build();
Request.Builder builder = Request.newBuilder();
builder.setType(Request.Type.LOGIN);
builder.setExtension(Protocol.login, login);
Request request = builder.build();
ch.writeAndFlush(request).sync();
服务端的主要代码.
switch (request.getType().getNumber()) {
case (Request.Type.LOGIN_VALUE):
System.out.println(request.getExtension(Protocol.login).getUser() + " "
+ request.getExtension(Protocol.login).getPswd());
break;
case (Request.Type.SERVICE_VALUE):
break;
default:
System.out.println("Don't know this type");
}
Response.Builder builder = Response.newBuilder();
builder.setResult("I am response result!");
ctx.writeAndFlush(builder.build()).sync();
要注意的是在服务端,你还要告诉netty,protobuf的extension如何解码.
ExtensionRegistry registry = ExtensionRegistry.newInstance();
Protocol.registerAllExtensions(registry);
ChannelPipeline p = ch.pipeline();
p.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
p.addLast("protobufDecoder",
new ProtobufDecoder(Protocol.Request.getDefaultInstance(),
registry));
p.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
p.addLast("protobufEncoder", new ProtobufEncoder());
以下是和worldclock例子中不同的地方.
ExtensionRegistry registry = ExtensionRegistry.newInstance();
Protocol.registerAllExtensions(registry);
p.addLast("protobufDecoder",
new ProtobufDecoder(Protocol.Request.getDefaultInstance(),registry));
参考:
https://developers.google.com/protocol-buffers/
http://blog.wolfman.com/articles/2011/11/23/how-to-implement-polymorphic-protocol-buffers-in-java
来源:oschina
链接:https://my.oschina.net/u/1449542/blog/205327