let crypto = require('crypto');
let http = require('http');

let app = http.createServer();
let sockets = [];  // 存放每一个客户端socket的数组

app.on('upgrade', (req, socket, head) => {
    socket.setEncoding('utf8');  // 统一socket的编码格式为utf8

    // 设置socket的header,升级协议
    const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
    const key = crypto.createHash('sha1')
        .update(req.headers['sec-websocket-key'] + GUID, 'binary')
        .digest('base64');
    const headers = [
        'HTTP/1.1 101 Switching Protocols',
        'Upgrade: websocket',
        'Connection: Upgrade',
        `Sec-WebSocket-Accept: ${key}`
    ];
    socket.write(headers.concat('', '').join('\r\n'));

    // 记录客户端socket相关信息
    sockets.push(socket);

    socket.on('data', function(data) {
        //进行广播,使每个客户端收到消息
        sockets.forEach(otherSocket => {
            // socket的通信handler和业务handler ...
            if (otherSocket !== socket) {
                // ...
            }
        });
    });
    socket.on('end', () => {
        // 结束socket时的handler
    });
    socket.on('close', () => {
        //当前客户端socket下线退出,清除相关信息
        let index = sockets.indexOf(socket);
        sockets.splice(index, 1);
    });
});
app.on('clientError', (err, socket) => {
    // 客户端错误时,结束socket连接
    socket.end('HTTP/1.1 400 Bad Request');
});

app.listen(4006);
本文作者:子匠_Zijor,转载请注明出处:http://www.dengzhr.com/node-js/1416