socket.io
クライアントをページごとに選択的に配置することを選択しない場合は、承認イベントを使用して、接続元のページを確認できます。
io.configure(function () {
io.set('authorization', function (handshakeData, callback) {
if (handshakeData.url == '/new') {
//allow the socket to connect
callback(null, true);
} else {
//prevent the socket handshake with an error
callback('socket.io is not accepting connections from this page', false);
}
});
});
コードでは、誰かがそのページをロードするたびio.sockets.on
にイベントにリスナーを追加しているため、オブジェクトを複数回使用しないでください。connection
さらに、ハンドシェイクが拒否された場合、connection
イベントは決して発生しないため、次のようなセットアップを使用できます。
io.sockets.on('connection', function(socket) {
//this shouldn't ever happen, it's the same object that was checked before
if (socket.handshake.url != '/new') {
socket.disconnect();
return;
}
//do something on page '/new'
}
app.get('/new', function(req, res) {
//sockets can successfully connect with this page
});
app.get('/foo', function(req, res) {
//sockets from this page will fail handshakes and be disconnected
});
ページ上のユーザー数をカウントする必要がある場合は、ソケットの接続イベントと切断イベントの両方をリッスンします。これは、それを行うための 1 つの方法です。
var pages = [];
io.sockets.on('connection', function(socket) {
if (pages[socket.handshake.url] == null) {
pages[socket.handshake.url] = 0;
}
pages[socket.handshake.url]++;
socket.on('disconnect', function() {
pages[socket.handshake.url]--;
});
}
人々が複数のタブを開いた場合、接続されたセッション Cookie を保存し、オブジェクトを使用して一致を探すことができsocket.handshake
ます。