1
我試圖連接用戶會話ID和創建的Cookie爲每個用戶登錄後連同它連接到套接字...任何方向或示例將是偉大的...我我正在使用nodejs,express,redis,socket.io和mongodb來處理我的其他數據庫。如何將用戶連接到套接字
這裏是在app.js文件中的代碼(但是我不確定它的一些)
var connect = require('connect');
var RedisStore = require('connect-redis')(express);
var redis = require("redis").createClient();
var io = require('socket.io');
var notificationsN = io.listen(server);
app.use(express.session({
secret: "secret sauce",
store: new RedisStore({ host: 'localhost', port: 3000, client: redis })
}));
//Not sure if below is correct actually... need to connect it with the current user... how do i go about doing that?
notificationsN.on('connection', function(client) {
const subscribe = redis
subscribe.subscribe('realtime');
subscribe.on('message', function(channel, message) {
client.send(message);
console.log('message received from ' + channel + " : " + message);
});
client.on('message', function(msg) {
console.log(msg);
});
client.on('disconnect', function() {
console.log('disconnecting from redis');
subscribe.quit();
});
});
這是客戶:
script(src='http://localhost:3000/socket.io/socket.io.js')
script.
var socket = io.connect('http://localhost/3000/');
socket.on('connect', function (data) {
setStatus('connected');
socket.emit('subscribe', { channel: 'realtime' });
});
socket.on('reconnecting', function(data) {
setStatus('reconnecting');
});
socket.on('message', function(data) {
console.log('received a message: ', data);
addMessage(data);
});
function addMessage(data) {
$('#notificationNumber').html(data);
}
function setStatus(msg) {
console.log('connection status: ' + msg);
}