我的来源
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();
最佳答案
我有个问题。 messageReceived()在哪里?
ProtobufVarint32FrameDecoder,ProtobufDecoder,ProtobufVarint32LengthFieldPrepender,ProtobufEncoder
净值分为四类。但是messageReceived()方法必须位于CustomHandler类中。和班级
必须添加ChannelPipeline的下一个实例。
例如)如果我为messageReceived()制作一个ProtobufHandler类(扩展SimpleChannelHandler),
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());
next.addLast("protobufHandler", new ProtobufHandler()); //add this.
抱歉,我的英语水平有限。