Skip to content

Commit 683fc73

Browse files
committed
add option to pick a random port by passing port 0
1 parent dfe8dc4 commit 683fc73

File tree

4 files changed

+29
-5
lines changed

4 files changed

+29
-5
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ A cross platform component for serving static assets with React Native.
3838

3939
## Usage
4040

41-
Declare the `StaticServer` with a port or use the default `9999`
41+
Declare the `StaticServer` with a port or use the default `0` to pick a random available port.
4242

4343
```javascript
4444
import StaticServer from 'react-native-static-server';
@@ -64,7 +64,7 @@ import RNFS from 'react-native-fs';
6464
// create a path you want to write to
6565
let path = RNFS.DocumentDirectoryPath + '/www';
6666

67-
let server = new StaticServer(8080, path);
67+
let server = new StaticServer(0, path);
6868
```
6969

7070
If the server should only be accessible from within the app, set `localOnly` to `true`

android/src/main/java/com/futurepress/staticserver/FPStaticServerModule.java

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,20 @@ public void start(String _port, String root, Boolean localhost, Promise promise)
7777
if (_port != null) {
7878
try {
7979
port = Integer.parseInt(_port);
80+
81+
if (port == 0) {
82+
try {
83+
port = this.findRandomOpenPort();
84+
} catch (IOException e) {
85+
port = 9999;
86+
}
87+
}
8088
} catch(NumberFormatException nfe) {
81-
port = 9999;
89+
try {
90+
port = this.findRandomOpenPort();
91+
} catch (IOException e) {
92+
port = 9999;
93+
}
8294
}
8395
}
8496

@@ -130,6 +142,18 @@ public void start(String _port, String root, Boolean localhost, Promise promise)
130142

131143
}
132144

145+
private Integer findRandomOpenPort() throws IOException {
146+
try {
147+
ServerSocket socket = new ServerSocket(0);
148+
int port = socket.getLocalPort();
149+
Log.w(LOGTAG, "port:" + port);
150+
socket.close();
151+
return port;
152+
} catch (IOException e) {
153+
return 0;
154+
}
155+
}
156+
133157
@ReactMethod
134158
public void stop() {
135159
if (server != null) {

index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55

66
const { FPStaticServer } = NativeModules;
77

8-
const PORT = "9999";
8+
const PORT = "0";
99
const ROOT = null;
1010
const LOCALHOST = 'http://127.0.0.1:';
1111

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

22
{
33
"name": "react-native-static-server",
4-
"version": "0.1.4",
4+
"version": "0.1.5",
55
"repository": "https://github.com/futurepress/react-native-static-server",
66
"description": "HTTP static file server for React Native",
77
"main": "index.js",

0 commit comments

Comments
 (0)