0
我這樣寫了一個簡單的ChannelHandler。通道處理程序沒有在netty 4.0上寫消息
public class SimpleServerHandler extends SimpleChannelInboundHandler<Object> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
ctx.write("It is " + new Date() + " now.\r\n");
ctx.flush();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush("=>complete");
System.out.println("complete");
};
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}
該處理器的作品顯示歡迎信息,如果客戶端(遠程登錄)連接到服務器。如果閱讀完整,則顯示完整的信息。 我嘗試連接服務器,但從服務器的任何消息響應(但我確認系統日誌)。
我不明白爲什麼。
P.S:我附上代碼啓動服務器
public class SimpleServer {
public static void main(String... args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);
b.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new SimpleServerHandler());
}
});
b.option(ChannelOption.SO_BACKLOG, 128);
b.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind("127.0.0.1", 8080).sync();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
謝謝。你是對的。我修正了它使用StringEncoder。另外,我可以將字符串轉換爲字節數組。 –