使用 protobuf 做为通信内容序列化的简单例子请看:http://www.cnblogs.com/ghj1976/p/5458176.html 。html
本文是使用 json 作为内容序列化的简单例子。java
新建例子项目,从 proto 文件产生 通信包的方式跟以前的彻底同样。git
本文的源码在:github
https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples/helloworld 这里的 json
HelloJsonServer.java 和 HelloJsonClient.java 这两个文件中。服务器
这个文件跟 protobuf 处理的文件不一样的地方以下:网络
整个类的定义文件以下:async
package com.ghj1976;ide
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import io.grpc.stub.AbstractStub;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.MethodDescriptor;
import io.grpc.protobuf.ProtoUtils;函数
/**
* Created by ghj1976 on 16/5/4.
*/
public class HelloWorldJSONStub extends AbstractStub<HelloWorldJSONStub>
implements io.grpc.examples.helloworld.GreeterGrpc.GreeterBlockingClient {
static final MethodDescriptor<HelloRequest, HelloReply> METHOD_SAY_HELLO =
MethodDescriptor.create(
GreeterGrpc.METHOD_SAY_HELLO.getType(),
GreeterGrpc.METHOD_SAY_HELLO.getFullMethodName(),
ProtoUtils.jsonMarshaller(HelloRequest.getDefaultInstance()),
ProtoUtils.jsonMarshaller(HelloReply.getDefaultInstance()));
protected HelloWorldJSONStub(Channel channel) {
super(channel);
}
protected HelloWorldJSONStub(Channel channel, CallOptions callOptions) {
super(channel, callOptions);
}
@Override
protected HelloWorldJSONStub build(Channel channel, CallOptions callOptions) {
return new HelloWorldJSONStub(channel, callOptions);
}
@Override
public HelloReply sayHello(HelloRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_SAY_HELLO, getCallOptions(), request);
}
}
具体的解析用的 ProtoUtils.jsonMarshaller() 这个函数。
服务器端代码封装个函数, bindService, 用于服务器的数据解析分层。
private ServerServiceDefinition bindService(final GreeterGrpc.Greeter serviceImpl){
return io.grpc.ServerServiceDefinition.builder(GreeterGrpc.SERVICE_NAME)
.addMethod(
com.ghj1976.HelloWorldJSONStub.METHOD_SAY_HELLO,
asyncUnaryCall(
new ServerCalls.UnaryMethod<HelloRequest,HelloReply>(){
@Override
public void invoke(HelloRequest request,StreamObserver<HelloReply> responseObserver){
serviceImpl.sayHello(request,responseObserver);
}
}
))
.build();
}
这里用到了咱们前面定义的方法
com.ghj1976.HelloWorldJSONStub.METHOD_SAY_HELLO,
增长服务时用这个 bindService 作封装。
服务端的代码改造就这些。
只须要修改 Stub 为咱们刚刚创建的 HelloWorldJSONStub 接口。
执行方法跟以前彻底同样, 启动 main 方法便可。
使用 Wireshark 监听网络请求,能够看到这时候发送的数据包:
客户端请求的数据包:
服务器端返回的包:
使用 protobuf 时,则会是以下的截图: