ServerSocket的accept()方法 [英] ServerSocket accept() method

查看:1298
本文介绍了ServerSocket的accept()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 sSocket = new ServerSocket(5050);
Socket socket = sSocket.accept();

推荐答案

图表不正确(并列在未经证实的勘误表

客户端随机选择端口(您不需要在Java中执行任何特殊操作)并在您指定的任何端口上连接到服务器。使用 netstat 命令行工具,您可以看到 - 首先,只是没有客户端的侦听服务器套接字:

The client chooses its port at random (you don't need to do anything special in Java) and connects to the server on whichever port you specified. Using the netstat command-line tool you can see this - 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)

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

Now with 1 client connecting from the local host (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
...

由于客户端是从同一台机器连接的,我们看到两个建立连接 - 一个从客户端到服务器(1),另一个从服务器到客户端(2)。它们具有相反的本地和外部地址(因为它们彼此交谈)并且您可以看到服务器端仍在使用端口5050,而原始服务器套接字(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-end is still using port 5050 while the original server socket (3) continues to listen on the same port.

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

(these are from the Mac, but Windows/Linux also have netstat giving similar output)

这篇关于ServerSocket的accept()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆