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
| const express = require('express'); const app = express(); const WebSocket = require('ws');
const serve = app.listen(3000,function () { console.log('server run 3000'); });
const ws = new WebSocket.Server({ server: serve });
let testData,clientsInfo = [],clientsUser = {};
app.get('/websocket/sendtoken', function(req, res){ console.log('data',req.query.token); testData = req.query.token; res.json({ msg: 'ok', token: req.query.token }) });
app.get('/websocket/clientsinfo', function(req, res){ res.json({ msg: 'ok', data: clientsInfo }) });
function allConnections(ws) { let i = 0; ws.clients.forEach(function each() { i+=1 }); console.log(`[SERVER] : 共有${i}个连接`); return i; }
ws.broadcast = function broadcast(data) { let num = allConnections(ws); ws.clients.forEach(function each(client) { client.send('广播'+data +'共有'+ num +'个用户'); }); console.log(`[SERVER] 收到客户端消息: ${data},共有${num}个用户`); }
ws.removeClientInfo = function removeClientInfo(clientsInfo,client) { let clientName = client.userName; clientsInfo.forEach(function (item,index) { if (item.userName === clientName){ clientsInfo.splice(index,1); } }); return clientsInfo; }
ws.on('connection', function (result) { console.log(`[SERVER] 客户端已连接`); result.on('message', function (message) { let res = JSON.parse(message); if (res.used === 'login'){ clientsUser[res.userName] = result; clientsInfo.push(res); result.send('from server' + res.userName + '已储存'); console.log(res.userName + '已储存'); } if(res.used === 'logout'){ delete clientsUser[res.userName]; ws.removeClientInfo(clientsInfo,res); result.send('from server' + res.userName + '已删除'); console.log(res.userName + '已删除'); } if(res.used === 'manage'){ let currentClients = JSON.stringify(clientsInfo); result.send(currentClients); console.log(res.userName + '信息已发送'); } if (res.used === 'send'){ let sendUser = clientsUser[res.userName]; sendUser.send('hello,world!') } if (res.used === 'sendall'){ console.log('接收到群发消息'); ws.clients.forEach(function each(client) { if (client !== result) { client.send('广播消息'); } }); }
}) result.on('close', function (closeResult) { console.log(`[SERVER] 客户端${closeResult}连接已关闭`); }); });
|