gpt4 book ai didi

java - netty echo 服务器发送消息,但我没有看到它

转载 作者:可可西里 更新时间:2023-11-01 02:42:34 25 4
gpt4 key购买 nike

我正在阅读默认手册 link我遇到了一个问题。我的回显服务器向客户端发送消息,但我没有看到它们。作为远程登录程序,我使用腻子。代码是一样的:

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();
}
}

cf.isSuccess() 是正确的,但在控制台 (putty) 中,我没有看到任何东西。如果我只想发送文本

ctx.writeAndFlush(Unpooled.copiedBuffer("Netty MAY rock!", CharsetUtil.UTF_8));
  • 它有效。但是,如果我尝试发送“msg”——我什么也得不到。预先感谢您的回复。

最佳答案

要读取和写入非 ByteBuf 消息,您需要解码器和编码器。

ch.pipeline().addLast(new LineBasedFrameDecoder(80))
.addLast(new StringDecoder())
.addLast(new StringEncoder())
.addLast(new DiscardServerHandler());

或者您可以手动解码和编码消息。将String编码成ByteBuf

ctx.writeAndFlush(Unpooled.copiedBuffer("Netty MAY rock!", CharsetUtil.UTF_8));

关于java - netty echo 服务器发送消息,但我没有看到它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32567275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com