加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java ServerSocket如何在接受客户端后获得绑定到同一本地端口的

发布时间:2020-12-15 02:17:40 所属栏目:Java 来源:网络整理
导读:我对Socket和ServerSocket端口的使用感到困惑. Oracle’s java tutorial about sockets说以下内容: What Is a Socket? Normally,a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits,l
我对Socket和ServerSocket端口的使用感到困惑. Oracle’s java tutorial about sockets说以下内容:

What Is a Socket?

Normally,a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits,listening to the socket for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request,the client tries to rendezvous with the server on the server’s machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.

If everything goes well,the server accepts the connection. Upon
acceptance,the server gets a new socket bound to the same local port

and also has its remote endpoint set to the address and port of the
client. It needs a new socket so that it can continue to listen to the
original socket for connection requests while tending to the needs of
the connected client.

On the client side,if the connection is accepted,a socket is successfully created and the client can use the socket to communicate with the server.
The client and server can now communicate by writing to or reading from their sockets.

我尝试了以下代码进行测试.但它引发了一个例外.

try {
    ServerSocket serverSocket = new ServerSocket(8080);

    Socket socket = serverSocket.accept();

    // This prints 8080
    System.out.println("Local port of accepted socket : " + socket.getLocalPort());  

    // But this throws java.net.BindException: Address already in use: JVM_Bind 
    Socket myClientSocket = new Socket("www.google.com",80,null,8080);

} catch (Exception e) {
    e.printStackTrace();
}

我的问题很明显.从serverSocket.accept()返回的套接字可以使用相同的本地端口(8080),为什么我创建的套接字不能使用它?

解决方法

为了简单起见,侦听TCP套接字已经明确绑定到端口,因此您无法将第二个TCP套接字显式绑定到同一端口(除非两个套接字也明确绑定到不同的IP地址,不包括INADDR_ANY).

接受的套接字不会通过明确的“绑定”过程.它们自动获取本地IP地址和端口,如果您在没有绑定的情况下连接它,则出站套接字也是如此.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读