Java ServerSocket accept() 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4307549/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:42:01  来源:igfitidea点击:

ServerSocket accept() method

java

提问by Eugene

Who knows how the port is chosen when I'm using accept method of ServerSocket class? Is it possible to define a range for the ports the method can choose from? Can I 'take' ports one by one just in order?

谁知道当我使用 ServerSocket 类的 accept 方法时如何选择端口?是否可以为方法可以选择的端口定义一个范围?我可以按顺序一个一个地“接收”端口吗?

ServerSocket sSocket = new ServerSocket(5050);
Socket socket = sSocket.accept();

From the book

从书中

采纳答案by SimonJ

The diagram is incorrect (and is listed in the unconfirmed errataon the O'Reilly site).

该图不正确(并列在O'Reilly 站点上未经证实的勘误表中)。

The clientchooses itsport at random (you don't need to do anything special in Java) and connects to the server on whichever port you specified. Using the netstatcommandline tool you can see this.

客户选择它的端口随机(你不需要做在Java中什么特别的东西),并连接到您指定的任何一个端口的服务器。使用netstat命令行工具可以看到这一点。

First, just the listening server socket with no clients:

首先,只是没有客户端的侦听服务器套接字:

simon@lucifer:~$ netstat -n -a
Active Internet connections (including servers)
Proto Recv-Q Send-Q  Local Address          Foreign Address     (state)
...
tcp46      0      0  *.5050                 *.*                 LISTEN
...

(there are lots of other entries, I've just removed the unrelated ones)

(还有很多其他条目,我刚刚删除了无关的条目)

Now with one client connecting from localhost (127.0.0.1):

现在有一个客户端从本地主机 (127.0.0.1) 连接:

simon@lucifer:~$ netstat -n -a
Active Internet connections (including servers)
Proto Recv-Q Send-Q  Local Address          Foreign Address     (state)
...
tcp4       0      0  127.0.0.1.64895        127.0.0.1.5050      ESTABLISHED <- 1
tcp4       0      0  127.0.0.1.5050         127.0.0.1.64895     ESTABLISHED <- 2
tcp46      0      0  *.5050                 *.*                 LISTEN      <- 3
...

Since the client is connecting from the same machine, we see two established connections - one from client to server (1), the other from server to client (2). They have opposite local and foreign addresses (since they're talking to each other) and you can see the server is still using port 5050 while the original server socket (3) continues to listen on the same port.

由于客户端从同一台机器连接,我们看到两个已建立的连接 - 一个从客户端到服务器 (1),另一个从服务器到客户端 (2)。它们具有相反的本地和外部地址(因为它们正在相互通信),您可以看到服务器仍在使用端口 5050,而原始服务器套接字 (3) 继续在同一端口上侦听。

(this output is from a Mac, but Windows/Linux also have netstatgiving similar output)

(此输出来自 Mac,但 Windows/Linux 也有netstat类似的输出)

回答by Codemwnci

The ServerSocketdefines the port as part of the constructor. If you do not specify a port, the socket is not bound (i.e. cannot be accessed).

所述的ServerSocket端口定义为构造的一部分。如果不指定端口,则套接字未绑定(即无法访问)。

To get the port of the connecting Socket, use getPort() and not getLocalPort(). The second one will give you the port on your server.

要获取连接 Socket 的端口,请使用 getPort() 而不是 getLocalPort()。第二个将为您提供服务器上的端口。

回答by khachik

You can pass 0as a port number to create a server socket on any free port, or make a method like this to create a server socket for any free port in the given range:

您可以传递0端口号以在任何空闲端口上创建服务器套接字,或者使用这样的方法为给定范围内的任何空闲端口创建服务器套接字:

public java.net.ServerSocket createServerSocket(int rangeStart, int rangeEnd)
                            throws java.io.IOException {
  for(int port=rangeStart; port<=randeEnd; port++) {  
    try {
      return new ServerSocket(port);
    } catch(java.net.BindException be) {
      // debug/warning here
      continue;
    }
  }
  throw new java.io.IOException("Failed to create a server socket, all ports between " +
                                rangeStart + " - " + rangeEnd + " are already in use.");
}

The loop doesn't take care of another exception (SecurityExceptionfor example), but you can add it.

循环不会处理另一个异常(SecurityException例如),但您可以添加它。

回答by thejh

A TCP connection consists of four parts:

TCP 连接由四部分组成:

  • Client IP
  • Client Port
  • Server IP
  • Server Port
  • 客户端IP
  • 客户端端口
  • 服务器IP
  • 服务器端口

There can be, for example, multiple clients connected to the same server port - as long as the clients don't have the same IP andthe same prt, it's ok. And for that part, the Operating System takes care.

例如,可以有多个客户端连接到同一个服务器端口 - 只要客户端没有相同的 IP相同的 prt,就可以。对于这一部分,操作系统会负责。

So it's totally ok to listen just on one port.

所以只在一个端口上收听是完全可以的。

回答by user207421

Youchose the port, when you said new ServerSocket(5050). All that stuff about using a different port for the accepted socket is 100% BS.

当您说 new ServerSocket(5050) 时,选择了端口。关于为接受的套接字使用不同端口的所有内容都是 100% BS。