[英]How client know which socket connect to?
I am using Java to do the socket programming as below. 我正在使用Java进行如下套接字编程。
Client program is as below: 客户程序如下:
Socket MyClient;
try {
MyClient = new Socket("Machine name", PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
Server program is as below: 服务器程序如下:
ServerSocket MyService;
try {
MyServerice = new ServerSocket(PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
Socket clientSocket = null;
try {
clientSocket = MyService.accept();
}
catch (IOException e) {
System.out.println(e);
}
Now my question is if I run more than one thread to open several sockets in one port (as the server code above), how my client program know which socket it is connecting to? 现在我的问题是,如果我运行多个线程在一个端口(如上面的服务器代码)中打开多个套接字,那么我的客户端程序如何知道它要连接到哪个套接字?
Your client connects to the Servers port. 您的客户端连接到服务器端口。 So all clients will be having the same code
MyClient = new Socket("Machine name", <port where server is listening>);
因此,所有客户端将具有相同的代码
MyClient = new Socket("Machine name", <port where server is listening>);
The port opened at client side is not important. 在客户端打开的端口并不重要。 The client will get a free port available in his OS.
客户端将在其OS中获得一个可用端口。
how my client program know which socket it is connecting to?
我的客户端程序如何知道它连接到哪个套接字?
The question doesn't make sense. 这个问题没有道理。 It doesn't 'connect to a socket' at all, it connects to a listening port, and there is only one of those.
它根本不“连接到套接字”,它连接到侦听端口,只有一个。 Your server only accepts one client, so the second and subsequent threads will get an undefined behaviour ranging from a ConnectException to a ConnectionException to nothing, most probably the latter.
您的服务器仅接受一个客户端,因此第二个及后续线程将获得未定义的行为,范围从ConnectException到ConnectionException到什么都没有,很可能是后者。
Your application knows it because you set it up with a specific port. 您的应用程序知道它,因为您使用特定端口进行了设置。 There is no "auto discovery" built into TCP/IP, it's up to you to pick a server-port and make sure you set your clients up to connect to that port.
TCP / IP中没有内置“自动发现”功能,这取决于您选择服务器端口并确保将客户端设置为连接到该端口。 Either you hard-code this into your client application or, better yet, have it in some configuration file you include with the client.
您可以将其硬编码到客户端应用程序中,或者更好地将其包含在客户端随附的某些配置文件中。
This is why you have a bunch of "known ports", like http is port 80. This means that a browser will always connect to port 80 on a web-server, unless you explicitly indicate another port in the URL. 这就是为什么有一堆“已知端口”(例如http是端口80)的原因。这意味着浏览器将始终连接到Web服务器上的端口80,除非您在URL中明确指出另一个端口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.