【发布时间】:2018-07-10 09:02:18
【问题描述】:
我正在尝试使用 Netty 构建一个简单的 TCP 客户端-服务器应用程序。 一开始我是这样通过SocketChannel从客户端发送消息的:
SocketChannel client = SocketChannel.open(hostAddress);
client.write(buffer);
所有消息都由服务器接收,但是当我想将响应写回客户端时,我看到为了获得客户端的响应,它需要通过引导程序发送消息并定义 Inboundhandler会阅读回复(也许有人知道另一种方式?) 当我尝试通过引导程序发送消息时,我使用以下代码:
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// TODO Auto-generated method stub
ch.pipeline().addLast(new TestClientHandler());
}
});
ChannelFuture future = bootstrap.connect(hostAddress);
future.channel().writeAndFlush(buffer);
但是这样服务器根本就没有收到消息! 这是我用于服务器的代码(当我不通过客户端的引导程序发送消息时工作正常):
bootstrap = new ServerBootstrap();
bootstrap.group(boosGroup, workerGroup);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(dnsMessageDecodingHandler);
pipeline.addLast(group,"DnsTcpHandler",dnsTcpHandler);
}
});
future = bootstrap.bind(hostAddress).await();
在 Netty 中编写简单的客户端-服务器的正确方法是什么?我没有找到任何可行的例子......
谢谢, 奥斯纳特。
【问题讨论】:
-
缺少 ServerBootstrap.bind() 调用?
-
有的,只是我没有复制
-
现在我也在客户端添加了绑定,但没有帮助
-
向服务器通道处理程序添加一个 LoggingHandler 并查看它是否调用了 bind()。如果绑定成功,请检查您的客户端是否可以访问您的地址
-
客户端和服务器都在我的电脑上运行在不同的端口...