简体   繁体   English

客户端应用程序如何找到服务器(Java)打开的动态选择的TCP端口?

[英]How can client application find dynamically selected TCP port opened by server (Java)?

I have a windows service which opens a TCP port (one that was available at given moment). 我有一个Windows服务,该服务打开一个TCP端口(在给定的时刻可用)。 Now I need to connect a client to that port. 现在,我需要将客户端连接到该端口。 How do I let the client know which port the server is running on? 如何让客户端知道服务器在哪个端口上运行?

Unless you have some way to communicate with the service from your Java program, this will not be that simple. 除非您有某种方法可以通过Java程序与服务进行通信,否则就不会那么简单。 One solution could be to try parsing the output of the netstat command. 一种解决方案是尝试解析netstat命令的输出。 For more details on how to do that you can look at this question 有关如何执行此操作的更多详细信息,请查看问题

You can't really solve this in the general case without either having the client try all the ports until it somehow recognizes the server, or communicating by some other method. 在一般情况下,除非让客户端尝试所有端口,直到客户端以某种方式识别服务器,或者通过其他方法进行通信,否则您无法真正解决此问题。

The easiest solution is to agree on a file name in an agreed location (the temp directory, for example) and store the port number in that file. 最简单的解决方案是在约定的位置(例如temp目录)中约定文件名,并将端口号存储在该文件中。

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

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