Search code examples
javaserverionettyserversocket

I'm getting java.net.BindException: Address already in use: bind when i try to listen and bind a client to same port


I'm getting the above exception while trying to establish a server and create a client to another server using the netty framework.

I have 2 java files:

  1. One is Server Acceptor meant to listen at a port say 9999

  2. and another class file Client Connector to connect to another server but bound with the port 9999.

Once both these files are executed I should be able to listen as a server in port 9999 and also send a message to remote server bound to same port 9999. Since the remote server guy accepts and sends message to same port of my server.(9999 in this case)

My ServerAcceptor.class runs successfully and listens in port 9999. But my ClientConnector.class complains that the port is already bound.

Now how can i send and receive in the same port?

My Client code is as below.

ClientTest clientTest =new ClientTest();
    EventLoopGroup group = new NioEventLoopGroup();
     Bootstrap bootstrap = new Bootstrap();
     bootstrap.group(group);
     bootstrap.channel(NioSocketChannel.class).handler(new MyClientHandler(clientTest));
     bootstrap.option(ChannelOption.TCP_NODELAY,true).option(ChannelOption.SO_REUSEADDR,true).option(ChannelOption.SO_KEEPALIVE, true);
    System.out.println("Connecting to Server");         

    ChannelFuture channelFuture;
    try {
        channelFuture = bootstrap.connect(new InetSocketAddress("localhost", 8888),new InetSocketAddress("localhost", 9999)).sync();
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture)
            throws Exception {
                System.out.println("Client");
            if (channelFuture.isSuccess()) {
            System.out.println("Client has connected successfully");
            } else {
            System.err.println("Client could not connect to the sever");
            channelFuture.cause().printStackTrace();
            }
            }
            } );

Solution

  • Once both these files are executed I should be able to listen as a server in port 9999 and also send a message to remote server bound to same port 9999.

    No you shouldn't. The system will not permit it. It will only permit inbound connections to share the listening port. Your requirement, assuming you have interpreted it correctly, is infeasible.

    Since the remote server guy accepts and sends message to same port of my server.(9999 in this case)

    This doesn't begin to make sense. If the remote server accepts connections, he will communicate over those connections, whatever their source port may have been. He doesn't care. Possibly what is really happening I s that he also listens on port 9999. In any case none of this imposes a requirement for you to specify a local outbound port.