diff options
author | 2019-10-18 20:53:41 +0200 | |
---|---|---|
committer | 2019-10-18 20:53:41 +0200 | |
commit | af506f40edb1c9c339cc86baf40baccf2dc6da62 (patch) | |
tree | d5efae2f9374ee11d645096208424d59812a9a58 /src/electron/ipc-api/localServer.js | |
parent | Merge branch 'develop' into local-server (diff) | |
download | ferdium-app-af506f40edb1c9c339cc86baf40baccf2dc6da62.tar.gz ferdium-app-af506f40edb1c9c339cc86baf40baccf2dc6da62.tar.zst ferdium-app-af506f40edb1c9c339cc86baf40baccf2dc6da62.zip |
Develop local server feature
Diffstat (limited to 'src/electron/ipc-api/localServer.js')
-rw-r--r-- | src/electron/ipc-api/localServer.js | 52 |
1 files changed, 52 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..2f8f1020a --- /dev/null +++ b/src/electron/ipc-api/localServer.js | |||
@@ -0,0 +1,52 @@ | |||
1 | import { ipcMain, app } from 'electron'; | ||
2 | import path from 'path'; | ||
3 | import net from 'net'; | ||
4 | import startServer from '../../server/start'; | ||
5 | |||
6 | const DEFAULT_PORT = 45569; | ||
7 | |||
8 | const portInUse = function (port) { | ||
9 | return new Promise((resolve) => { | ||
10 | const server = net.createServer((socket) => { | ||
11 | socket.write('Echo server\r\n'); | ||
12 | socket.pipe(socket); | ||
13 | }); | ||
14 | |||
15 | server.listen(port, '127.0.0.1'); | ||
16 | server.on('error', () => { | ||
17 | resolve(true); | ||
18 | }); | ||
19 | server.on('listening', () => { | ||
20 | server.close(); | ||
21 | resolve(false); | ||
22 | }); | ||
23 | }); | ||
24 | }; | ||
25 | |||
26 | let localServerStarted = false; | ||
27 | |||
28 | export default (params) => { | ||
29 | ipcMain.on('startLocalServer', () => { | ||
30 | if (!localServerStarted) { | ||
31 | // Find next unused port for server | ||
32 | let port = DEFAULT_PORT; | ||
33 | (async () => { | ||
34 | // eslint-disable-next-line no-await-in-loop | ||
35 | while (await portInUse(port) && port < DEFAULT_PORT + 10) { | ||
36 | port += 1; | ||
37 | } | ||
38 | console.log('Starting local server on port', port); | ||
39 | |||
40 | startServer( | ||
41 | path.join(app.getPath('userData'), 'server.sqlite'), | ||
42 | port, | ||
43 | ); | ||
44 | |||
45 | params.mainWindow.webContents.send('localServerPort', { | ||
46 | port, | ||
47 | }); | ||
48 | })(); | ||
49 | localServerStarted = true; | ||
50 | } | ||
51 | }); | ||
52 | }; | ||