-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathws.js
97 lines (80 loc) · 2.33 KB
/
ws.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
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const WebSocket = require('ws');
// npm install ws
// npm install openssl-self-signed-certificate
// node /data/ws.js
// node D:\prj\spdjs\ws.js 8888
var https = require('https');
var selfSigned = require('openssl-self-signed-certificate');
var options = {
key: selfSigned.key,
cert: selfSigned.cert
};
console.log('==>createServer options');
console.log(options);
// 创建request请求监听器
const processRequest = (req, res) => {
res.writeHead(200);
res.end('ok,u r already receive cert,u can test WebSockets!\n');
};
var args = process.argv.splice(2)
console.log(args);
const server = https.createServer(options, processRequest).listen(args[0]);
//console.log(`HTTPS started on port ${port + 1} (dev only).`);
const wss = new WebSocket.Server({ server });
wss.broadcast = function broadcast(msg) { //服务端广播消息
console.log('--->wss.clients');
//console.log('wss.clients.length::'+wss.clients.size);
// console.log(wss.clients);
//wss.clients is a set not an array. Use wss.clients.size.
wss.clients.forEach(function each(client) {
try {
if (client.readyState == WebSocket.OPEN) {
var retstr = JSON.stringify(msg);
client.send(retstr);
}
// client.send(msg);
} catch (e) {
console.log('received: %s', e);
}
});
//end foreach
/*
global.conns.forEach((wsConn, i) => {
// console.log(v);
try {
var retstr = JSON.stringify(json.msg);
console.log('conns .forEach send:' + retstr);
wsConn.send(retstr);
} catch (e) {
wsConn.send('except:' + e);
}
} );
//end foreach
*/
}
//global.conns = new Array();
// {method:"testsend",msg:{"aa":1111}}
wss.on('connection', function connection(ws) {
// global.conns.push(ws);
ws.on('message', function incoming(message) {
console.log('received: %s', message);
try {
var json = eval('(' + message + ')');
if (json.method == "testsend") {
wss.broadcast(json.msg);
//end if
}
else
// throw "cant find method ";
//ws.send('server ws send:' + message);
wss.broadcast(message);
} catch (e) {
wss.broadcast(message);
// ws.send('except:' + e);
}
});
ws.send('conn ok');
});
//end wss.conn
//wss.broadcast();
console.log("fff")