Node.js chat
I've recently set up a nodejs chat server, the chat client is served by a php server. When users log in, their sessions will be stored in mysql of the php server, and a login cookie will append to browser.
I want to restrict users that only logged in users are able to chat. What is the best practice to archieve that ?
My quick thought:
When the chat client loaded, if user logged in, I'll send the login cookie information to nodejs verver via socket. Then create a nodejs session. When user chat, the message together with cookie information will be sent to nodejs server via socket. If the cookie information does not match the nodejs session, the message will not be broadcasted and client socket will be disconected.
A websocket is a permanent open connection. You only need to autheticate once when you connect to the websocket.
Simply send your login cookie to node.js once and store it on the server with a reference to the socket connection. Then only handle messages from authenticated users and only broadcast to authenticated users.
The problem is that client side users can easily fake this cookie as node does not talk to php to ensure that it's a valid login cookie.
An example using now.
warning pseudo code
// server.js
everyone.now.joinChat = function(cookie) {
chat.add(this, cookie);
}
everyone.now.serverMessage = function(message) {
if (chat.hasUser(this)) {
chat.broadcast(message);
}
}
chat = (function() {
var users = [];
return {
"add": function(client) {
users.push(client);
},
"hasUser": function(client) {
return users.some(function(user) {
return user === client;
});
},
"broadcast": function(message) {
users.each(function(user) {
user.clientMessage(message);
});
}
}
}());
// client.js
$(function() {
now.joinChat($.cookie("login"));
$("#send").click(function() {
now.serverMessage($(this).data("message"));
});
now.clientMessage = function(message) {
$("#messages").append($("<span></span>").text(message));
}
});
这是我正在寻找nodeJS的答案 - 如何使用express创建和读取会话
链接地址: http://www.djcxy.com/p/6482.html上一篇: foo [T](T,T)的拓宽/推理:T
下一篇: Node.js聊天