generated from ulivz/ts-lib-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
43 lines (38 loc) · 1.17 KB
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { createServer } from 'http';
import { Server as SocketServer, Socket } from 'socket.io';
import { ServerPort } from './port';
import { Unport } from '../../src';
// 1. Initialize a port
const serverPort: ServerPort = new Unport();
// 2. Implement a Channel based on underlying IPC capabilities
const server = createServer();
const io = new SocketServer(server, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
});
const sockets: Record<string, Socket> = {};
const channel = serverPort.implementChannel({
send: message => {
Object.values(sockets).forEach(socket => {
socket.emit('message', message);
});
},
});
io.on('connection', (socket: Socket) => {
sockets[socket.id] = socket;
socket.on('disconnect', () => {
delete sockets[socket.id];
});
socket.on('message', message => channel.pipe(message));
});
server.listen(10101);
// 3. You get a complete typed Port with a unified interface 🤩
serverPort.onMessage('syn', payload => {
console.log('[child] [syn]', payload.pid);
serverPort.postMessage('ack', { pid: 'child' });
});
serverPort.onMessage('body', payload => {
console.log('[child] [body]', JSON.stringify(payload));
});