如何使用netty客户端编写消息?

时间:2018-01-31 09:45:37

标签: netty

我正在尝试使用Netty构建一个简单的TCP客户端 - 服务器应用程序。 一开始,我通过SocketChannel以这种方式从客户端发送消息:

    SocketChannel client = SocketChannel.open(hostAddress);
    client.write(buffer);

所有消息都是由服务器接收的,但是当我想将响应写回客户端时,我看到为了得到客户端的响应,它需要通过bootstrap发送消息并定义Inboundhandler会读取回复(也许有人知道另一种方式吗?) 当我尝试通过bootstrap发送消息时,我使用以下代码:

    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中编写简单客户端服务器的正确方法是什么?我没有找到任何可行的例子......

谢谢, Osnat。

3 个答案:

答案 0 :(得分:0)

您应该了解TCP连接的工作原理

本文介绍了典型的TCP流程。 https://www.ibm.com/support/knowledgecenter/en/SSB23S_1.1.0.14/gtps7/s5tcpcf.html

查看文章后,您需要正确编写服务器代码

// create your server bootstrap
ServerBootstrap b = new ServerBootstrap();

// add your ChannelInitializer which handles when client has been connected to your server
// in ChannelInitializer you need to register your ChannelHandler, such as ChannelDuplexHandler to client channel pipeline
b.childHandler(YOUR_CHANNEL_INITIALIZER); 

b.bind(bindAddress); // your server will now listen() for client connect()

运行bootstrap代码后,客户端可以连接到服务器

答案 1 :(得分:0)

netty存储库中有多个示例,我不确定为什么你说没有。

https://github.com/netty/netty/tree/4.1/example

那说我怀疑问题是你不是等待&#34;直到connect(...)操作完成。如果您要检查writeAndFlush(...)返回的ChannelFuture结果,它会告诉您这个。

SSo快速修复将是:

ChannelFuture future = bootstrap.connect(hostAddress).await();
future.channel().writeAndFlush(buffer);

答案 2 :(得分:0)

在我检查了从writeAndFlush返回的ChannelFuture的原因之后(就像Norman Maurer建议的那样),我看到原因是:不支持的消息类型:HeapByteBuffer(预期:ByteBuf,FileRegion) 这是因为我没有将ObjectEncoder添加到客户端管道! 这个补充解决了这个问题:         b.handler(新的ChannelInitializer(){

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            // TODO Auto-generated method stub
            ch.pipeline().addLast(new ObjectEncoder());
            ch.pipeline().addLast(new TestClientHandler());
        }

      });

感谢所有帮助过我的人! Osnat。

相关问题