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 () {
.......
});
......
});其它:
- 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 */ }
參考:
- https://socket.io/docs/v3/server-instance/
The Server instance | Socket.IO - https://stackoverflow.com/questions/6458083/get-the-clients-ip-address-in-socket-io
node.js - Get the client's IP address in socket.io - Stack Overflow - https://socket.io/docs/v3/server-api/index.html#socket-handshake
Server API | Socket.IO
沒有留言:
張貼留言