在阅读Netty教程时,我发现一个简单的描述如何集成Netty和Google Protocol Buffers。我开始研究该示例(因为文档中没有更多信息),并编写了一个类似于本地时间应用程序的简单应用程序。但是该示例在PipeFactory类中使用静态初始化,例如:
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.protobuf.ProtobufDecoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import static org.jboss.netty.channel.Channels.pipeline;
/**
* @author sergiizagriichuk
*/
class ProtoCommunicationClientPipeFactory implements ChannelPipelineFactory {
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline p = pipeline();
p.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
p.addLast("protobufDecoder", new ProtobufDecoder(Communication.DataMessage.getDefaultInstance()));
p.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
p.addLast("protobufEncoder", new ProtobufEncoder());
p.addLast("handler", new ProtoCommunicationClientHandler());
return p;
}
}
请看第p.addLast("protobufDecoder", new ProtobufDecoder(Communication.DataMessage.getDefaultInstance()));
行代码。我了解到 ClientBootstrap
class 只能创建一个工厂(pipeline factory),即 bootstrap.setPipelineFactory()
方法。因此,在这种情况下,我只能使用一个消息来发送给服务器,只能接收一个消息,这对于我来说很不好,而且我认为不仅仅是我一个人遇到这个问题。那么,如何在一个连接中使用不同的消息进行发送和接收呢?也许我可以像这样创建几个 protobufDecoder
。p.addLast("protobufDecoder", new ProtobufDecoder(Communication.DataMessage.getDefaultInstance()));
p.addLast("protobufDecoder", new ProtobufDecoder(Communication.TestMessage.getDefaultInstance()));
p.addLast("protobufDecoder", new ProtobufDecoder(Communication.SrcMessage.getDefaultInstance()));
或者其他技术吗? 非常感谢。