13
13
import java .io .InputStream ;
14
14
import java .io .InputStreamReader ;
15
15
import java .io .OutputStreamWriter ;
16
+ import java .net .Socket ;
16
17
import java .net .URL ;
17
18
import java .net .URLConnection ;
18
19
import java .util .HashMap ;
@@ -149,6 +150,19 @@ public void setWorkDir(String workDir) {
149
150
this .workDir = workDir ;
150
151
}
151
152
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
+
152
166
/**
153
167
* @param handler class name of a instance of NginxJavaRingHandler
154
168
* @param options default options are
@@ -167,8 +181,9 @@ public void setWorkDir(String workDir) {
167
181
* "server-user-defined", "",
168
182
* "location-user-defined", ""
169
183
* </pre>
184
+ * @return the listening port
170
185
*/
171
- public void start (String handler , final Map <String , String > options ) {
186
+ public int start (String handler , final Map <String , String > options ) {
172
187
173
188
Map <String , String > moptions = ArrayMap .create (
174
189
"error-log" , "logs/error.log" ,
@@ -188,6 +203,9 @@ public void start(String handler, final Map<String, String> options) {
188
203
"location-user-defined" , ""
189
204
);
190
205
for (Map .Entry <String , String > entry : options .entrySet ()) {
206
+ if (entry .getKey ().equals ("port" ) && entry .getValue ().equals ("0" )) {
207
+ entry .setValue (pickFreePort ()+"" );
208
+ }
191
209
if (moptions .containsKey (entry .getKey ())) {
192
210
moptions .put (entry .getKey (), entry .getValue ());
193
211
}else {
@@ -265,7 +283,7 @@ public void start(String handler, final Map<String, String> options) {
265
283
} catch (IOException e ) {
266
284
throw new RuntimeException ("can not getCanonicalPath of conf file for nginx-clojure embed server!" , e );
267
285
}
268
-
286
+ return Integer . parseInt ( moptions . get ( "port" ));
269
287
}
270
288
271
289
public void start (final String workDir , final String cfg ) {
0 commit comments