gpt4 book ai didi

java - Netty channel 读取未调用

转载 作者:行者123 更新时间:2023-11-30 08:18:38 32 4
gpt4 key购买 nike

我正在尝试让多个 Netty 客户端相互通信。我在尝试这个时遇到了问题。当我写入 channel 时,它不会调用 NettyClientHandler#channelRead

NettyClient 类:

public class NettyClient
{
private static NettyClient client;
private int port;
private Channel channel;

public NettyClient(int port)
{
this.port = port;
}

public static void start(final int port)
{
BungeeCord.getInstance().getScheduler().runAsync(AzideaCord.getInstance(), new Runnable()
{
@Override
public void run()
{
client = new NettyClient(port);
client.run();
}
});
}

private void run()
{
EventLoopGroup group = new NioEventLoopGroup();

try
{
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new NettyClientInitializer());

channel = bootstrap.bind(port).sync().channel();
System.out.println("[Netty] Connected to localhost:" + port + ".");
channel.write("test" + "\r\n");
}
catch(InterruptedException e)
{
e.printStackTrace();
}
finally
{
group.shutdownGracefully();
}
}
}

NettyClientHandler 类:

public class NettyClientHandler extends ChannelInboundHandlerAdapter
{
// Never called
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
{
System.out.println("Msg: " + msg);
}
}

NettyClientInitializer 类:

public class NettyClientInitializer extends ChannelInitializer<SocketChannel>
{
@Override
protected void initChannel(SocketChannel channel) throws Exception
{
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new NettyClientHandler());
}
}

最佳答案

您需要更换:

channel.write("test" + "\r\n");

channel.writeAndFlush("test" + "\r\n");

关于java - Netty channel 读取未调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29305904/

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