我得到 java.net.BindException:地址已在使用:当我尝试侦听并将客户端绑定到同一端口时绑定

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

我在尝试建立 server 并使用 netty 框架为另一台服务器创建 client 时遇到上述异常。

我有 2 个 java 个文件:

  1. 一个是 Server Acceptor 意思是听 port9999

  2. 和另一个 class 文件 Client Connector 连接到另一个 服务器但与 port 9999.

  3. 绑定

一旦这两个文件都被执行,我应该能够作为 port 9999 中的服务器进行监听,并向绑定到相同 port 9999 的远程服务器发送消息。 由于远程服务器人员接受消息并将消息发送到我服务器的同一端口。(在这种情况下为9999

我的 ServerAcceptor.class 成功运行并监听 port 9999。但是我的 ClientConnector.class 抱怨端口已经绑定。

现在如何在同一端口发送和接收?

我的客户端代码如下。

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

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.

不,你不应该。系统不允许。它只允许 inbound 连接共享监听端口。你的要求,假设你已经正确解释了它,是不可行的。

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

这开始没有意义。如果远程服务器接受连接,他将通过这些连接进行通信,无论它们的源端口是什么。他不在乎。可能真正发生的事情是他也在端口 9999 上侦听。无论如何 none 这强加了您指定本地出站端口的要求。