简体   繁体   English

在java中为tcp连接获取一个打开的套接字

[英]Getting an open socket for tcp connection in java

I'm developing a torrent with Java and there is a small question I have.我正在用 Java 开发一个 torrent,我有一个小问题。 How can I get an open socket for my process in java?如何在java中为我的进程获取一个打开的套接字? I need about 100 free sockets in a sequence, just like 10000-10100.我按顺序需要大约 100 个空闲套接字,就像 10000-10100 一样。 All I know is that by using我所知道的是,通过使用

socket = new Socket(ip, port);

We need to provide ip and port.我们需要提供ip和端口。 Well of course this is the case of debug and my ip is loopback, but I could find only one free port by using random numbers in port field.嗯,当然这是调试的情况,我的 ip 是环回,但我只能通过在端口字段中使用随机数找到一个空闲端口。 Please tell me how to find a sequence of free ports for tcp.请告诉我如何为 tcp 找到一系列空闲端口。

You can't guarantee free port numbers.您不能保证免费的端口号。 You will have to scan the ports on the machine looking for free ports anywhere between 1024 and 65535. If you want to create a client socket you would have to try and connect from each local port you want in sequence, aborting and starting again if you encounter a used port - but of course this could keep happening if another application is trying to grab ports too.您将不得不扫描机器上的端口,寻找 1024 到 65535 之间任意位置的空闲端口。如果您想创建一个客户端套接字,您必须尝试从您想要的每个本地端口依次进行连接,如果您这样做,则中止并重新启动遇到一个使用过的端口——当然,如果另一个应用程序也试图获取端口,这种情况可能会继续发生。 For a server socket, you would have to try and bind to each port in sequence.对于服务器套接字,您必须尝试按顺序绑定到每个端口。

For a client socket, do you need to specify the local port?对于客户端套接字,是否需要指定本地端口? If not, just allocate the number of connections you want.如果没有,只需分配您想要的连接数。 For a server socket, I would simply assume that I owned all ports from, say 10000 to 10100. Although starting a hundred servers probably isn't what you want to do.对于服务器套接字,我会简单地假设我拥有从 10000 到 10100 的所有端口。虽然启动一百个服务器可能不是你想要做的。

With any networking in Java, rather than using the Java .net package, rather use Netty which is much easier to work with.使用 Java 中的任何网络,而不是使用 Java .net 包,而是使用更容易使用的Netty

Why do you need a range of port numbers at the client?为什么在客户端需要一系列端口号 You can get a free listening port via new ServerSocket(0) and interrogating the local port.您可以通过 new ServerSocket(0) 获得一个免费的侦听端口并询问本地端口。 But there's no good reason why you should need a range of client port numbers (other than over-enthusiastic outbound firewall rules, which netadmins sometimes specify without realizing there is no API to use them).但是没有充分的理由为什么您应该需要一系列客户端端口号(除了过于热情的出站防火墙规则,网络管理员有时会在没有意识到没有 API 可以使用它们的情况下指定这些规则)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM