-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
44 lines (33 loc) · 1010 Bytes
/
index.js
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
43
44
const express = require('express');
const http = require('http');
const path = require('path');
const { Server } = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// app.use(express.static(path.join(__dirname, 'public')));
const port = 4200;
const sockets = new Map();
io.on("connection", (client) => {
sockets.set(client.id, client);
console.log('New websocket connection');
client.on('messageFromClient', (msg) => {
console.log(msg);
io.emit('messageFromServer', msg);
});
client.on('disconnect', () => {
sockets.delete(client.id);
console.log('New websocket disconnected');
});
});
app.get('/', (_, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.post('/', (_, res) => {
console.log('POST')
io.emit('messageFromServer', 'Hello from server');
res.json({ success: true });
});
server.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});