我在使用Netty 3.9时遇到了问题,我已经建立了一个客户端,一旦连接到服务器就会发送/执行编码器。但是,它只是连接而不发送编码器。
ClientHandler的
public final class ClientHandler extends IdleStateAwareChannelUpstreamHandler {
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
Channel channel = ctx.getChannel();
logger.info("Channel connected: " + channel);
}
}
ClientPipelineFactory
private final ClientHandler handler = new ClientHandler();
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("handler", handler);
pipeline.addLast("encoder", new HandshakeEncoder());
return pipeline;
}
HandshakeEncoder
public final class HandshakeEncoder extends OneToOneEncoder {
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
ChannelBuffer buffer = ChannelBuffers.buffer(1);
buffer.writeByte(49);
return buffer;
}
}
答案 0 :(得分:0)
只有在向Channel写入内容时才会调用编码器。我想你想要的是扩展SimpleChannelUpstreamHandler并使用类似的东西:
public final class HandshakeHandler extends SimpleChannelUpstreamHandler {
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
Channel channel = ctx.getChannel();
ChannelBuffer buffer = ChannelBuffers.buffer(1);
buffer.writeByte(49);
channel.write(buffer);
}
}