Java netty echo服务器发送消息,但我不';我看不出来
我正在浏览默认手册,遇到了一个问题。我的echo服务器向客户端发送消息,但我看不到它们。作为telnet程序,我使用putty。 代码相同:Java netty echo服务器发送消息,但我不';我看不出来,java,tcp,network-programming,client-server,netty,Java,Tcp,Network Programming,Client Server,Netty,我正在浏览默认手册,遇到了一个问题。我的echo服务器向客户端发送消息,但我看不到它们。作为telnet程序,我使用putty。 代码相同: public class DiscardServerHandler extends ChannelInboundHandlerAdapter { // (1) @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2) ChannelFutur
public class DiscardServerHandler extends ChannelInboundHandlerAdapter { // (1)
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
ChannelFuture cf = ctx.write(msg);
ctx.flush();
if (!cf.isSuccess()) {
System.out.println("Send failed: " + cf.cause());
}else{
System.out.println("Send worked.");
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}
二等舱:
public class DiscardServer {
private int port;
public DiscardServer(int port) {
this.port = port;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new DiscardServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(port).sync(); // (7)
// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
new DiscardServer(port).run();
}
}
- 它起作用了。但如果我尝试发送“msg”-我什么也得不到。 提前感谢您的回复
ch.pipeline().addLast(new LineBasedFrameDecoder(80))
.addLast(new StringDecoder())
.addLast(new StringEncoder())
.addLast(new DiscardServerHandler());
或者您可以手动解码和编码消息。将字符串编码为ByteBuf
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty MAY rock!", CharsetUtil.UTF_8));
您在这里提到的同一代码正在正常工作。测试它
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty MAY rock!", CharsetUtil.UTF_8));