-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpress.js
More file actions
70 lines (60 loc) · 1.55 KB
/
Copy pathexpress.js
File metadata and controls
70 lines (60 loc) · 1.55 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const express = require('express')
// const express = require('express');
const WebSocket = require('ws');
const http = require('http');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// 存储所有活跃的连接
const clients = new Set();
// static server
app.use(express.static('dist'));
// need cors
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
function broadcast(message, sender) {
for (let client of clients) {
if (client !== sender && client.readyState === WebSocket.OPEN) {
try {
const msgObj = JSON.parse(message);
if(Array.isArray(msgObj)){
const type = msgObj[0].type || 'default';
const msg = msgObj.map(i => i.msg).join('\n');
client.send(JSON.stringify({
type,
msg
}));
}else{
const {type, msg} = msgObj;
client.send(JSON.stringify({
type: type || 'default',
msg: `${msg}`
}));
}
} catch (error) {
client.send(JSON.stringify({
type: 'error',
msg: `Error in message format`
}));
}
}
}
}
wss.on('connection', function(ws) {
clients.add(ws);
ws.on('message', function(message) {
// console.log('Received: %s', message);
broadcast(message, ws);
});
ws.on('close', function() {
clients.delete(ws);
});
ws.on('error', function(e) {
console.log('WebSocket error: ', e);
});
});
server.listen(8796, () => {
console.log('Listening on http://localhost:8796');
});