java serversocket 类如何在同一端口上为多个客户端连接提供服务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3729794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does serversocket class serve multiple client connections on same port?
提问by keshav84
When using a Socket class one is establishing a TCP connection to a server on some port, but on the server the ServerSocket is capable of handling multiple client connections for each accept request and delegate it to a thread to server the request. But how is it possible for a ServerSocket class to accept multiple tcp connections on the same port.
当使用 Socket 类时,在某个端口上建立到服务器的 TCP 连接,但在服务器上,ServerSocket 能够为每个接受请求处理多个客户端连接,并将其委托给一个线程来处理请求。但是 ServerSocket 类怎么可能在同一个端口上接受多个 tcp 连接。
Does it mean that it is upto the OS to decide how many connections it allows or what is the maximum backlog allowed and can this be controlled by applications on top of OS(i mean is java restricted by the maximum backlog supported by OS) and is there any privison for backlog connections in TCP specification?
这是否意味着由操作系统决定它允许多少连接或允许的最大积压是多少,这是否可以由操作系统之上的应用程序控制(我的意思是 Java 受操作系统支持的最大积压限制)并且是TCP 规范中对积压连接有任何限制吗?
Best reagards,
Keshav
最佳reagards,
凯沙夫
采纳答案by zigdon
A TCP connection is defined by a unique set of (source IP, source port, dest IP, dest port). Since the server binds to a particular port, it defines two of those 4 variables. As long as the clients all come from different IPs and/or different ports, it won't be an issue.
TCP 连接由一组唯一的(源 IP、源端口、目标 IP、目标端口)定义。由于服务器绑定到特定端口,因此它定义了这 4 个变量中的两个。只要客户端都来自不同的 IP 和/或不同的端口,就不会有问题。
And yes, the OS can control how many total connections are allowed, and your program can restrict that even further.
是的,操作系统可以控制允许的总连接数,您的程序可以进一步限制。
回答by Colin Hebert
It serves multiple clients and you can choose how many clients you will handle a the same time.
它为多个客户提供服务,您可以选择同时处理多少个客户。
A connection (aka a Socket
between a client and a server isn't only identified by the ServerIP/ServerPort, it's identified with ClientIP/ClientPort/ServerIP/ServerPort.
连接(即Socket
客户端和服务器之间的连接不仅由 ServerIP/ServerPort 标识,还由 ClientIP/ClientPort/ServerIP/ServerPort 标识。
You only have to accept connections (and usually treat them in different threads).
您只需要接受连接(并且通常在不同的线程中处理它们)。
By default the backlog size is 50, but you can set it when you create your ServerSocket
.
默认情况下,backlog 大小为 50,但您可以在创建ServerSocket
.
new ServerSocket(21, 100); //Create a server socket with a backlog of 100
Resources :
资源 :
回答by Steve Emmerson
The operating-system on which the server runs uses the remote port number to distinguish between the various connections to the server.
运行服务器的操作系统使用远程端口号来区分与服务器的各种连接。