本來以為自己對websocket 還是掌握一些堂氯,但是突然發(fā)現(xiàn)別人寫的服務(wù)器在連接的時(shí)候就可以獲得token占哟,自己還是太菜了士修,所以整理一個(gè)女责,主要是新的websocket在監(jiān)聽connection
的時(shí)候可以多一個(gè)req參數(shù) 那么在url中就能可以拿到連接帶過來的參數(shù)了耳鸯,學(xué)無止境瓣赂。nodejs威武
var _ = require('lodash');
var qs = require('qs');
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 9999 });
let list = [];
wss.on('connection', function connection(ws,req) { //用于獲取連接時(shí)候的參數(shù) eg: ws://ip:port/path?token=xxxxxx
let url = req.url;
console.log('url is ' + url); // "/path?token=xxxxxx"
let prarms = qs.parse(_.split(url,'?')[1]); // token=xxxxxx
console.log('url is ' + JSON.stringify(prarms));// {token:xxxxxxx}
list.push(ws);
ws.on('message', function incoming(message) {
console.log('收到數(shù)據(jù)' + message);
ws.send('server get message' + message);
console.log('數(shù)據(jù)發(fā)送成功');
});
ws.on('error', function (error) {
console.log('錯(cuò)誤' + error);
});
ws.on('open', function (e) {
ws.send('open');
});
ws.on('close', function (e) {
_.pull(list, ws);
console.log('在線人數(shù)' + list.length);
})
});