Skip to content

Commit 8c2d22e

Browse files
committed
pick a free port when port is 0
1 parent bd30a21 commit 8c2d22e

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

nginx-clojure-embed/src/java/nginx/clojure/embed/NginxEmbedServer.java

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import java.io.InputStream;
1414
import java.io.InputStreamReader;
1515
import java.io.OutputStreamWriter;
16+
import java.net.Socket;
1617
import java.net.URL;
1718
import java.net.URLConnection;
1819
import java.util.HashMap;
@@ -149,6 +150,19 @@ public void setWorkDir(String workDir) {
149150
this.workDir = workDir;
150151
}
151152

153+
public static int pickFreePort() {
154+
Socket s = new Socket();
155+
try {
156+
s.bind(null);
157+
int port = s.getLocalPort();
158+
s.setReuseAddress(true);
159+
s.close();
160+
return port;
161+
} catch (IOException e) {
162+
throw new RuntimeException("can not pickFreePort", e);
163+
}
164+
}
165+
152166
/**
153167
* @param handler class name of a instance of NginxJavaRingHandler
154168
* @param options default options are
@@ -167,8 +181,9 @@ public void setWorkDir(String workDir) {
167181
* "server-user-defined", "",
168182
* "location-user-defined", ""
169183
* </pre>
184+
* @return the listening port
170185
*/
171-
public void start(String handler, final Map<String, String> options) {
186+
public int start(String handler, final Map<String, String> options) {
172187

173188
Map<String, String> moptions = ArrayMap.create(
174189
"error-log", "logs/error.log",
@@ -188,6 +203,9 @@ public void start(String handler, final Map<String, String> options) {
188203
"location-user-defined", ""
189204
);
190205
for (Map.Entry<String, String> entry : options.entrySet()) {
206+
if (entry.getKey().equals("port") && entry.getValue().equals("0")) {
207+
entry.setValue(pickFreePort()+"");
208+
}
191209
if (moptions.containsKey(entry.getKey())) {
192210
moptions.put(entry.getKey(), entry.getValue());
193211
}else {
@@ -265,7 +283,7 @@ public void start(String handler, final Map<String, String> options) {
265283
} catch (IOException e) {
266284
throw new RuntimeException("can not getCanonicalPath of conf file for nginx-clojure embed server!", e);
267285
}
268-
286+
return Integer.parseInt(moptions.get("port"));
269287
}
270288

271289
public void start(final String workDir, final String cfg) {

0 commit comments

Comments
 (0)