diff options
Diffstat (limited to 'src/electron/ipc-api/localServer.js')
-rw-r--r-- | src/electron/ipc-api/localServer.js | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/electron/ipc-api/localServer.js b/src/electron/ipc-api/localServer.js new file mode 100644 index 000000000..d12fb5708 --- /dev/null +++ b/src/electron/ipc-api/localServer.js | |||
@@ -0,0 +1,51 @@ | |||
1 | import { ipcMain, app } from 'electron'; | ||
2 | import net from 'net'; | ||
3 | import startServer from '../../server/start'; | ||
4 | |||
5 | const DEFAULT_PORT = 45569; | ||
6 | |||
7 | const portInUse = function (port) { | ||
8 | return new Promise((resolve) => { | ||
9 | const server = net.createServer((socket) => { | ||
10 | socket.write('Echo server\r\n'); | ||
11 | socket.pipe(socket); | ||
12 | }); | ||
13 | |||
14 | server.listen(port, '127.0.0.1'); | ||
15 | server.on('error', () => { | ||
16 | resolve(true); | ||
17 | }); | ||
18 | server.on('listening', () => { | ||
19 | server.close(); | ||
20 | resolve(false); | ||
21 | }); | ||
22 | }); | ||
23 | }; | ||
24 | |||
25 | let localServerStarted = false; | ||
26 | |||
27 | export default (params) => { | ||
28 | ipcMain.on('startLocalServer', () => { | ||
29 | if (!localServerStarted) { | ||
30 | // Find next unused port for server | ||
31 | let port = DEFAULT_PORT; | ||
32 | (async () => { | ||
33 | // eslint-disable-next-line no-await-in-loop | ||
34 | while (await portInUse(port) && port < DEFAULT_PORT + 10) { | ||
35 | port += 1; | ||
36 | } | ||
37 | console.log('Starting local server on port', port); | ||
38 | |||
39 | startServer( | ||
40 | app.getPath('userData'), | ||
41 | port, | ||
42 | ); | ||
43 | |||
44 | params.mainWindow.webContents.send('localServerPort', { | ||
45 | port, | ||
46 | }); | ||
47 | })(); | ||
48 | localServerStarted = true; | ||
49 | } | ||
50 | }); | ||
51 | }; | ||