动态选择端口号? [英] Dynamically choosing port number?

查看:161
本文介绍了动态选择端口号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我需要获取一个端口号,以便在同一程序的多个实例之间进行通信。
现在,我可以简单地选择一些固定的数字并继续使用它。但我想知道是否有办法动态选择端口号,这样我就不必为设置端口号而烦扰我的用户。

In Java, I need to grab a port number for communication between multiple instances of the same program. Now, I could simply pick some fixed number and go with it. But I'm wondering if there's a way to dynamically choose the port number, so that I don't have to bother my users with setting the port number.

这是一个我的想法,其工作方式如下:

Here's one idea I had, which works like this:


  • 有一个固定的初始端口号A.

  • 程序'MyApp'启动,尝试抓取端口A.

  • 如果成功,则它是'MyApp'的第一个实例。完成。

  • 如果失败,它会通过端口A询问A上的程序是否是MyApp的实例。如果是,请与该实例通信。完成。如果没有,请尝试抓住端口A + 1。如果有另一个使用该端口的程序(也不是'MyApp'的实例),那么抓A + 2,然后A + 3,依此类推。

  • There's a fixed initial port number A.
  • Program 'MyApp' starts, tries to grab port A.
  • If it succeeds, then it's the first instance of 'MyApp'. Done.
  • If it fails, it asks over port A whether the program on A is an instance of 'MyApp'. If yes, communicate with that instance. Done. If not, try to grab port A+1. And if there's another program using that port (not an instance of 'MyApp' either), then grab A+2, then A+3, and so on.

这种策略有意义吗?或者有更好的方法来动态选择端口号吗?

Does this strategy make sense? Or is there a better way to dynamically choose a port number?

推荐答案

如果绑定到端口0,Java将使用系统生成的端口。 :-)所以,如果您已经使用了所需的端口,这可能是最简单的方法。

If you bind to port 0, Java will use a system-generated port. :-) So, that's probably the easiest way to fall back if your desired port is already used.

ServerSocket s = new ServerSocket(0);
int port = s.getLocalPort();    // returns the port the system selected

这篇关于动态选择端口号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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