简体   繁体   English

使用调试侦听端口启动进程内JVM。 如何检查端口是否繁忙

[英]Starting an in process JVM with debug listening port. How to check if a port is busy

I use the function JNI_CreateJavaVM to create, on windows, an in-process JVM into an executable. 我使用函数JNI_CreateJavaVM在Windows上将进程内JVM创建为可执行文件。 I also pass some options to turn on debugging, in particular: 我还传递了一些选项来打开调试,特别是:

-Xrunjdwp:transport=dt_socket,server=y,address=666,suspend=n

along with some other options. 以及其他一些选项。 This works fine . 这很好用

The problem I have though is if I start two versions of the executable: JNI_CreateJavaVM crashes. JNI_CreateJavaVM的问题是,如果我启动两个版本的可执行文件: JNI_CreateJavaVM崩溃。 The obvious fix is to check if port 666 is busy and, if so, use a different port number. 明显的解决方法是检查端口666是否繁忙,如果繁忙,请使用其他端口号。 Except I don't know how to do this! 除了我不知道该怎么做!

So, my question: how can I check if a port is being listened on already? 所以,我的问题是:如何检查端口是否已经被监听?

Don't test for port-in-use in advance. 不要提前测试使用中的端口。 Just let your application do what it wants to do, and catch the exception there. 只需让您的应用程序执行它想做的事情,然后在那里捕获异常即可。 The situation can change between the time you test and when you actually try to use the port. 在测试时间和实际尝试使用端口之间,情况可能会发生变化。

Furthermore, if you are trying to write a server application, you can have the operating system automatically pick a free port for you. 此外,如果您尝试编写服务器应用程序,则可以让操作系统自动为您选择一个空闲端口。 From the JavaDoc for http://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html 从JavaDoc中获取http://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html

Creates a server socket, bound to the specified port. 创建绑定到指定端口的服务器套接字。 A port number of 0 means that the port number is automatically allocated, typically from an ephemeral port range. 端口号0表示通常从临时端口范围自动分配该端口号。 This port number can then be retrieved by calling getLocalPort. 然后可以通过调用getLocalPort检索此端口号。

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

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