简体   繁体   中英

How to write messages using netty client?

I am trying to build a simple TCP client-server application using Netty. At the beginning I send the messages from the client via SocketChannel in this way:

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

All the messages were received by the server, but when I wanted to write the response back to the client, I saw that in order to get the response by the client it need to send the message via bootstrap and to define Inboundhandler that will read the response (maybe someone knows another way?) When I tried to send a message via bootstrap I use the following code:

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

But in this way the server didn't get the message at all! This is the code I am using for the server (that works fine when I send the message not via the client's bootstrap):

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

What is the right way to write a simple client-server in Netty? I didn't find any working examples that do it...

Thanks, Osnat.

You should know about how TCP connection works

This article describes typical TCP flow. https://www.ibm.com/support/knowledgecenter/en/SSB23S_1.1.0.14/gtps7/s5tcpcf.html

After looking at the article you need to write server code correctly

// 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()

After running bootstrap code, client can be connected to server

There are multiple examples in the netty repository, I am not sure why you say there are none.

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

That said I suspect the problem is that your not "wait" until the connect(...) operations completes. If you would check the ChannelFuture result returned by writeAndFlush(...) it would have told you this.

SSo a quick fix would be:

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

After I checked the cause of the ChannelFuture that returned from the writeAndFlush (like Norman Maurer advised me to), I saw that the cause is: unsupported message type: HeapByteBuffer (expected: ByteBuf, FileRegion) This was because I didn't add an ObjectEncoder to the client pipeline!! This addition solved the problem: b.handler(new ChannelInitializer() {

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

      });

Thanks for all the people that helped me! Osnat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM