我目前正在开发一个即时消息应用程序,但在保存登录服务器的用户时遇到问题。我知道我必须存储每个连接用户的连接事件的套接字资源,但是当我在不同的浏览器上访问服务器时,我无法拥有所有这些资源。
问题
这是服务器的一部分:
//..
//..
var users = {};
io.sockets.on('connection', function (socket) {
users[req.session.name] = socket;
socket.on('msgToServer', function (data) {
users[data['to']].emit('msgFromServer',{message:data['message'],to:data['from'],from:data['to']});
});
});
当我从一个使用一个会话的浏览器向另一个使用另一个会话的浏览器发送消息时.. 代码中断:
C:\Archivos de programa\nodejs\session\data_handler.js:142
users[data['to']].emit('msgFromServer',{message:data['message'],to:data['from
^
TypeError: Cannot call method 'emit' of undefined at Socket.<anonymous> (C:\Archivos de programa\nodejs\session\data_handler.js:142:20)
因为如果我使用一个帐户(例如 charlie)登录,服务器会保留
var users = {};
io.sockets.on('connection', function (socket) {
users['charlie'] = socket; <-- charlie's socket resource
如果我从查理登录的浏览器发送消息,则 users['charlie'] 可用 ... only,所以就像 charlie 只能向自己发送消息,因为用户对象中没有更多的套接字资源,所以当我尝试向 pedros 的帐户发送消息,例如......该资源不可用(未定义)并且服务器抛出该错误。我需要的是一种让所有用户从一个用户代理登录的方法......在一个容器中,不一定是一个对象,在这种情况下:用户。因此 data['to'] 不会是未定义的,并且 msgFromServer 事件可以任意发送给用户:
服务器
var express = require('express');
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
app.use(express.static( __dirname));
app.use(express.bodyParser());
app.use(express.cookieParser());
var MemcachedStore = require('connect-memcached')(express);
app.use(express.session({
secret: 'lolz',
store:new MemcachedStore
}));
var connection = function(){
var mysql = require('mysql');
var mysql = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: '',
});
mysql.query('use test');
return mysql;
};
app.post('/data', function(req, res){
var username = req.body.username;
var password = req.body.password;
var mysql = connection();
mysql.query("select username from user where username like '"+ username +"' and password like '"+password +"'",
function(err, result, fields) {
if (err) throw err;
else {
if(result != ''){
req.session.name = username;
mysql.query("update user set online = 1 where id like '"+req.session.name+"' ");
res.redirect("/welcome_user");
}
else{
res.end("You are not registered");
}
}
});
});
app.get("/welcome_user",function(req,res){
var html = '<html>\n'+
'<head>\n'+
'<link rel="stylesheet" type="text/css" href="styles/jquery-ui-1.8.18.custom.css">\n'+
'<link rel="stylesheet" type="text/css" href="styles/styles.css">\n'+
'<style> \n #onlineUsers{border: 1px solid black; width: 300px;}</style>\n'+
'<script src="http://127.0.0.1/socket.io/lib/socket.io.js"></script>\n'+
'<script src="scripts/jquery.js"></script>\n'+
'<script type="text/javascript" src="scripts/jquery-ui-1.8.18.custom.min.js"></script>\n'+
'<script src="scripts/chatbox.js"></script>\n'+
'<script src="scripts/send.js"></script>\n'+
'<script>\n'+
"//receive();\n"+
'$(function(){\n'+
'$("#onlineUsers li").dblclick( function(event){\n '+"createChatbox($.trim($(this).text()), '"+req.session.name+"','');\n"+
'} );'+
'});'+
'</script>\n'+
'</head>\n'+
'<body>\n'+
'<h1>Hola '+req.session.name+'. Estos son los usuarios en linea </h1> \n'+'<div id="onlineUsers"><ol>\n';
mysql = connection();
mysql.query("select username from user where online = 1 and username != '"+req.session.name+"' ",
function(err, results, fields) {
if (err) throw err;
for (var index in results) {
html += '<li>' + results[index].username + '</li>';
}
html +='</ol></div> \n'+
'</body>\n'+
'</html>';
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
}
);
var users = {};
io.sockets.on('connection', function (socket) {
users[req.session.name] = socket;
socket.on('msgToServer', function (data) {
for (var u in users){
console.log("%s | %s",u,users[u]);
/*
this is how I determine that the user that logged in
is not available in the user object
*/
}
users[data['to']].emit('msgFromServer' {message:data['message'],to:data['from'],from:data['to']});
});
});
});
server.listen(80);
客户:
function createChatbox(to,from,message){
$('<div id ="chatbox" class='+to+'> <div id="messageOutput" > <textarea class="readOnly" readonly="readonly" rows="4" cols="30"></textarea></div><br /> <hr /> <div id="messageInput"> <textarea class ="editable" rows="2" cols="30"> </textarea> </div> </div>').appendTo("body").dialog({draggable:true, title:to}) ;
if(message !='')
$('#chatbox.'+to+' #messageOutput textarea.readOnly').text(message);
$("textarea.editable").keydown(function(event){
if(event.which == 13 && $(this).val() != ''){
send(to,from,$.trim($(this).val()));
$(this).val('');
return false;
}
});
}
var socket = io.connect('http://localhost');
function send(to, from, message){
socket.emit('msgToServer',{message:message,to:to,from:from});
}
socket.on('msgFromServer', function (data) {
message = data['message'],
from = data['from'],
to = data['to'];
if($('#chatbox.'+from).dialog("isOpen") === true){
$('#chatbox.'+from+' #messageOutput textarea.readOnly').text(message);
}
else if(($('#chatbox.'+from).dialog("isOpen") !== true)){
createChatbox(from,to,message);
}
});