Java ServerSocket如何在接受客户端后获得绑定到同一本地端口的新套接字?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java ServerSocket如何在接受客户端后获得绑定到同一本地端口的新套接字?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2151字,纯文字阅读大概需要4分钟。
内容图文
![Java ServerSocket如何在接受客户端后获得绑定到同一本地端口的新套接字?](/upload/InfoBanner/zyjiaocheng/767/29641684458040019eaa7f4c65883c52.jpg)
我对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地址和端口,如果您在没有绑定的情况下连接它,则出站套接字也是如此.
内容总结
以上是互联网集市为您收集整理的Java ServerSocket如何在接受客户端后获得绑定到同一本地端口的新套接字?全部内容,希望文章能够帮你解决Java ServerSocket如何在接受客户端后获得绑定到同一本地端口的新套接字?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。