[英]Can two threads call a new socket (client socket) in the same port?
What should happen if a Thread instantiates a new client Socket while other Thread is handling another client Socket connected to the same port? 如果一个线程实例化一个新的客户端套接字,而另一个线程正在处理连接到同一端口的另一个客户端套接字,应该怎么办? This Threads are part of the same Java program.
该线程是同一Java程序的一部分。
Not sure if you asking about client or server socket. 不确定是否询问客户端或服务器套接字。 But I'll answer both.
但是我都会回答。 If you try to open a listening server socket on the same port - you'll get
java.net.BindException thrown: Address already in use (Bind failed)
or something similar. 如果尝试在同一端口上打开侦听服务器套接字,则会
java.net.BindException thrown: Address already in use (Bind failed)
或类似的东西。 If you are connecting to a port - it works fine if the server accepts multiple clients. 如果要连接到端口-如果服务器接受多个客户端,则可以正常工作。
And it does not matter if it is same thread, different thread or another process. 并且是相同的线程,不同的线程还是另一个进程都没有关系。
A Socket
has two ports – a local port and a remote port . Socket
具有两个端口- 本地端口和远程端口 。 These are called source port and destination port in the TCP specification . 在TCP规范中,这些端口称为源端口和目标端口 。
When you connect to a server, you specify the host name and the (remote) port. 连接到服务器时,您可以指定主机名和(远程)端口。 The server needs to know where to send the responses, which is why the client will also have a (local) port.
服务器需要知道将响应发送到哪里,这就是为什么客户端还将有一个(本地)端口的原因。 The local port is assigned by the operating system from the pool of free ports.
本地端口由操作系统从可用端口池中分配。
Try this code sample: 尝试以下代码示例:
import java.io.IOException;
import java.net.Socket;
public class SocketTest {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
final int j = i;
new Thread(() -> {
try {
Thread.sleep(100 * j);
try (Socket socket = new Socket("stackoverflow.com", 80)) {
System.out.printf("%d -> %d%n", socket.getLocalPort(), socket.getPort());
}
} catch (InterruptedException | IOException ignored) {}
}).start();
}
}
}
The output of one execution on my machine looks like this: 我的机器上一次执行的输出如下所示:
36699 -> 80 36700 -> 80 36701 -> 80 36703 -> 80 36708 -> 80 36709 -> 80 36710 -> 80 36712 -> 80 36713 -> 80 36714 -> 80
The local ports will generally vary each time. 本地端口通常每次都会变化。
In conclusion: The client doesn't care how many sockets are connected to the same remote address. 结论:客户端不在乎有多少套接字连接到同一远程地址。 There won't be any collision between the local ports, either.
本地端口之间也不会发生任何冲突。
Further reading: 进一步阅读:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.