简体   繁体   中英

How to send data on a particular Netty Client instance running on different port

I have written a basic Netty Client that sends and receives data from a server. But I have started two instances of the Client on ports 8080 and 8081. Now how can I send a particular string on port 8080 and another string on 8081. I am confused in how to send the data on a particular port. I can able to send all the strings to the server. But I want to specify which string to be sent on which port to which server. Like I want to send "Hello server1" to server1 on port 8080 and "Hello server2" to server2 on port 8081. How can I do that?

My Netty Client :

public class Client implements  Runnable {

public int port;

private Channel channel;
public  ChannelFuture channelFuture = null;
private String message;
int rcvBuf, sndBuf, lowWaterMark, highWaterMark;

public Client(int port) {

    this.port = port;
    rcvBuf = Integer.MAX_VALUE;
    sndBuf = Integer.MAX_VALUE;
    lowWaterMark = 2048;
    highWaterMark = 3048;

}

@Override
public void run() {

    try {
        connectLoop();
    } catch (Exception ex) {

        System.err.println("Exception raised in Client class" + ex);
     }

}

public final void connectLoop() throws InterruptedException {
    EventLoopGroup workGroup = new NioEventLoopGroup();

    try {
        Bootstrap bs = new Bootstrap();
        bs.group(workGroup);
        bs.channel(NioSocketChannel.class);
        bs.option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.SO_RCVBUF, rcvBuf)
                .option(ChannelOption.SO_SNDBUF, sndBuf)
                .option(ChannelOption.SO_LINGER, 0)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(lowWaterMark, highWaterMark))
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) {
                        socketChannel.pipeline()
                                .addLast("patternDecoder", new ClientDecoder())
                                .addLast("Response Handler", new ClientHandler())// for receiving from Server
                                .addLast("exception Handler", new ClientExceptionHandler(port));
                    }
                });

        channelFuture = bs.connect("127.0.0.1", port).sync();
        this.channel = channelFuture.channel();
        if (channelFuture.isSuccess()) {
            sendMessage("Hello server");
        }
    } catch (Exception ex) {

        workGroup.shutdownGracefully();
        System.err.println("ERROR : Server Not In Connection");
        System.err.println("Connecting to Server...");
                   reconnect();
    }

}

public void reconnect() throws InterruptedException {
    Thread.sleep(10000);
    connectLoop();

}

public void sendMessage(String data){
    if (data != null) 
    {
       channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer(data.getBytes()));
       System.out.println("Outgoing  To  Server  >> " + data);
    }
}
public static void main(String[] args){
    Thread t = new Thread(new Client(8080));
    t.start();
    Thread t1 = new Thread(new Client(8081));
    t1.start();
}

}

Client Handler

public class ClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, final String message) throws Exception {

        System.out.println("Incoming From Server  >> " + message);
        ctx.channel().writeAndFlush(Unpooled.wrappedBuffer("HELLO".getBytes()));
    }
}

ClientExceptionHandler

 public class ClientExceptionHandler extends ChannelInboundHandlerAdapter {

    private int port;
    public ClientExceptionHandler(int port){
        this.port = port;
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

       ctx.deregister();
       ctx.disconnect();
       ctx.close();
       System.err.println("ERROR : Server Disconnected");
       System.err.println("Reconnecting to Server...");
    }
}

First you need to understand how ports work. Only servers will listen on specific ports. In your example server will listen from port 8080. Then multiple clients can connect to port 8080. Since you haven't given specific details, I suggest you to try one of the following.

  • Run two servers, one listens for port 8080 and other listens for port 8081. Then use two clients as you suggested.
  • Run only one server on port 8080 and connect two similar clients If you want to differentiate between clients use some kind of a message (eg send client id to server)

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