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
| var express = require('express'); var app = express(); var server = require('http').Server(app); var websocket = require('ws');
app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); });
var wss = new websocket.Server({ server });
wss.broadcast = function broadcast(s, ws) { wss.clients.forEach(function each(client) { if (s == 1) { client.send(ws.name + ":" + ws.msg); } if (s == 0) { client.send(ws + "退出聊天室"); } }); };
wss.on('connection', function(ws) { ws.send('你是第' + wss.clients.size + '位'); ws.on('message', function(jsonStr, flags) { var obj = eval('(' + jsonStr + ')'); this.user = obj; if (typeof this.user.msg != "undefined") { wss.broadcast(1, obj); } }); ws.on('close', function(close) { try { wss.broadcast(0, this.user.name); } catch (e) { console.log('连接断开'); } }); });
server.listen(4000, function() { console.log('listening on *:4000'); });
|