我的源 TestMessage - 是我的 protobuf 对象
@Override
public ChannelPipeline getPipeline() {
ChannelPipeline next = Channels.pipeline();
next.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
next.addLast("protobufDecoder", new ProtobufDecoder(TestMessage.getDefaultInstance()));
next.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
next.addLast("protobufEncoder", new ProtobufEncoder());
return next;
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
Channel ch = e.getChannel();
if (ch.isOpen()) {
TestMessage req = (TestMessage) e.getMessage();
System.out.println(req.getMessage());
ch.close();
}
}
发送
Socket fromserver = new Socket("localhost", 7283);
PrintWriter out = new PrintWriter(fromserver.getOutputStream(), true);
TestMessage.Builder message = TestMessage.newBuilder();
message.setMessage("message .....");
message.build();
out.println(message);
out.close();
fromserver.close();