2021年6月11日 星期五

Node.js socket.io

let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let cookie = require('cookie');
let ws_port = 9999;
//設定監聽IPv4的IP,避免取remote IP連IPv6一起取(::ffff:192.168.96.1)
http.listen(ws_port, '0.0.0.0', function () {
    console.log('listening on *:' + ws_port);
});

const test_io = io.of('/test');

test_io.on('connection', function (socket) {
    //client連線數量
    let client_cnt = io.engine.clientsCount;
    
    //取得 query 參數(GET 參數)
    let aa = socket.handshake.query['aa'];
    
    //取得 cookie
    let cookies = '';
    try {
        cookies = cookie.parse(socket.handshake.headers.cookie);
    } catch (err) {
        console.log('#無效cookie:', socket.handshake.headers.cookie);
        console.log(err);
    }
    
    //取得IP
    let client_ip = socket.request.connection.remoteAddress;
    
    //取得header資訊
    if (undefined !== socket.handshake.headers["x-real-ip"]) {
        client_ip = socket.handshake.headers["x-real-ip"];
    }


    socket.on('disconnect', async function () {
        ......
    });
    
    async function main() {
        ......
    }
    main().catch(err => {
        .....
        socket.disconnect(true);
    });
    
    socket.on('testmsg', function () {
        .......
    });

    ......
});


其它:
  1. socket.handshake 物件內的資料
    {
      headers: /* the headers sent as part of the handshake */,
      time: /* the date of creation (as string) */,
      address: /* the ip of the client */,
      xdomain: /* whether the connection is cross-domain */,
      secure: /* whether the connection is secure */,
      issued: /* the date of creation (as unix timestamp) */,
      url: /* the request URL string */,
      query: /* the query params of the first request */,
      auth: /* the authentication payload */
    }

 

參考:



沒有留言:

張貼留言