-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathserver.js
More file actions
271 lines (218 loc) · 7.69 KB
/
Copy pathserver.js
File metadata and controls
271 lines (218 loc) · 7.69 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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
const WebSocket = require('ws'); // socket.io 支持的协议版本(4)和 微信小程序 websocket 协议版本(13)不一致,所以选用ws
const Redis = require('ioredis');
const fs = require('fs');
const ini = require('ini');
const jwt = require('jsonwebtoken');
const url = require('url');
const mysql = require('mysql');
const config = ini.parse(fs.readFileSync('./.env', 'utf8')); // 读取.env配置
const redis = new Redis({
port: env('REDIS_PORT', 6379), // Redis port
host: env('REDIS_HOST', '127.0.0.1'), // Redis host
// family: 4, // 4 (IPv4) or 6 (IPv6)
password: env('REDIS_PASSWORD', null),
db: 0,
});
const ws = new WebSocket.Server({
port: 6001,
clientTracking: false,
verifyClient({req}, cb) {
try {
const urlParams = url.parse(req.url, true);
const token = urlParams.query.token || req.headers.authorization.split(' ')[1];
const jwtSecret = env('JWT_SECRET');
const algorithm = env('JWT_ALGO', 'HS256');
const {sub, nbf, exp} = jwt.verify(token, jwtSecret, {algorithm});
if (Date.now() / 1000 > exp) {
cb(false, 401, 'token已过期.')
}
if (Date.now() / 1000 < nbf) {
cb(false, 401, 'token未到生效时间.')
}
if (!sub) {
cb(false, 401, '无法验证令牌签名.')
}
cb(true)
} catch (e) {
console.info(e);
cb(false, 401, 'Token could not be parsed from the request.');
}
},
});
const clients = {};
ws.on('connection', (ws, req) => {
try {
const urlParams = url.parse(req.url, true);
const token = urlParams.query.token || req.headers.authorization.split(' ')[1];
const jwtSecret = env('JWT_SECRET');
const algorithm = env('JWT_ALGO', 'HS256');
const {sub, exp} = jwt.verify(token, jwtSecret, {algorithm});
const uuid = sub;
ws.uuid = uuid;
ws.exp = exp;
if (!clients[uuid]) {
clients[uuid] = [];
}
clients[uuid].push(ws);
if (/^\d{1,15}$/.test(String(uuid))) {
userLogged(ws, req); // 记录用户登录
}
} catch (e) {
console.info(e.message);
ws.close();
}
ws.on('message', message => { // 接收消息事件
if (ws.uuid) {
console.info('[%s] message:%s %s', getNowDateTimeString(), ws.uuid, message);
}
if (ws.exp && Date.now() / 1000 > ws.exp) {
ws.close();
}
});
ws.on('close', () => { // 关闭链接事件
if (ws.uuid) {
console.info('[%s] closed:%s', getNowDateTimeString(), ws.uuid);
const wss = clients[ws.uuid];
if (wss instanceof Array) {
const index = wss.indexOf(ws);
if (index > -1) {
wss.splice(index, 1);
if (/^\d{1,15}$/.test(String(ws.uuid))) {
userLoggedOut(ws, req); // 用户退出
}
if (wss.length === 0) {
delete clients[ws.uuid];
}
}
}
}
});
});
// redis 订阅
redis.psubscribe('*', function (err, count) {
});
redis.on('pmessage', (subscrbed, channel, message) => { // 接收 laravel 推送的消息
console.info('[%s] %s %s', getNowDateTimeString(), channel, message);
const {event} = JSON.parse(message);
const uuid = channel.split('.')[1];
const wss = clients[uuid];
switch (event) {
case 'Illuminate\\Notifications\\Events\\BroadcastNotificationCreated':
case 'App\\Events\\WechatScanLogin':
if (wss instanceof Array) {
wss.forEach(ws => {
if (ws.readyState === 1) {
ws.send(message);
}
});
}
break;
}
});
function env(key, def = '') {
return config[key] || def
}
function getNowDateTimeString() {
const date = new Date();
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}
function clearUsersOnline() {
const connection = mysqlConnection();
const sql = 'truncate table users_online';
connection.query(sql, function (err) {
});
connection.end();
}
async function userLogged(ws, req) {
const connection = mysqlConnection();
try {
const result = await new Promise((resolve, reject) => {
const sql = 'SELECT * FROM users_online WHERE user_id = ? LIMIT 1';
connection.query(sql, [ws.uuid], function (err, result) {
if (err) {
console.log('[SELECT ERROR] - ', err.message);
return reject(err);
}
resolve(result);
});
});
const ip = getClientIp(req);
const now = getNowDateTimeString();
const wss = clients[ws.uuid];
const stackLevel = wss.length;
console.info(stackLevel);
if (result.length === 0) {
const sql = 'INSERT INTO users_online (user_id, ip, stack_level, created_at, updated_at) VALUES (?, ?, ?, ?, ?)';
connection.query(sql, [ws.uuid, ip, stackLevel, now, now], function (err) {
if (err) {
console.log('[SELECT ERROR] - ', err.message);
throw new Error(err);
}
});
} else {
const sql = 'UPDATE users_online set ip = ?, stack_level = ?, updated_at = ? WHERE user_id = ?';
connection.query(sql, [ip, stackLevel, now, ws.uuid], function (err) {
if (err) {
console.log('[SELECT ERROR] - ', err.message);
throw new Error(err);
}
});
}
} catch (e) {
console.info(e.message);
}
connection.end();
}
function userLoggedOut(ws, req) {
const connection = mysqlConnection();
const now = getNowDateTimeString();
const wss = clients[ws.uuid];
const stackLevel = wss.length;
try {
if (stackLevel === 0) {
const sql = 'DELETE FROM users_online WHERE user_id = ?';
connection.query(sql, [ws.uuid], function (err) {
if (err) {
console.log('[SELECT ERROR] - ', err.message);
throw new Error(err);
}
});
} else {
const sql = 'UPDATE users_online set stack_level = ?, updated_at = ? WHERE user_id = ?';
connection.query(sql, [stackLevel, now, ws.uuid], function (err) {
if (err) {
console.log('[SELECT ERROR] - ', err.message);
throw new Error(err);
}
});
}
} catch (e) {
console.info(e.message);
}
connection.end();
}
function getClientIp(req) {
return req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
}
function mysqlConnection() {
const dbConfig = {
user: env('DB_USERNAME'),
password: env('DB_PASSWORD'),
database: env('DB_DATABASE'),
charset: 'utf8mb4',
};
const unixSocket = env('DB_SOCKET');
if (unixSocket) {
dbConfig.socketPath = unixSocket;
} else {
dbConfig.host = env('DB_HOST', 'localhost');
dbConfig.port = env('DB_PORT', 3306);
}
const connection = mysql.createConnection(dbConfig);
connection.connect();
return connection;
}
clearUsersOnline();