我在本文中使用了 mike 编写的 node.js 的多房间聊天应用程序示例。并将其更改为使用从 php 会话处理程序中获取的会话数据,直到现在
这是我到目前为止写的代码的一部分
var express = require('express'),
app = express(),
memcache = require("memcache"),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server),
co = require("./cookie.js"),
php = require('phpjs'),
codein = require("node-codein");
//check if user loggedin
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
var cookieManager = new co.cookie(req.headers.cookie);
var client = new memcache.Client(11211, "localhost");
client.connect();
user = client.get("sessions/"+cookieManager.get("sec_session_id"), function(error, result){
var session = JSON.parse(result);
user = JSON.parse(session.name);
user = user.username;
storeUsername(user);
});
});
function storeUsername(user){
// usernames which are currently connected to the chat
var usernames = {};
io.of('/private').authorization(function (handshakeData, callback) {
console.dir(handshakeData);
handshakeData.foo = 'baz';
callback(null, true);
}).io.sockets.on('connection', function (socket) {
usernames[socket.id] = socket;
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.emit('updatechat', socket.username, data);
});
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function(username){
// we store the username in the socket session for this client
socket.username = user;
// add the client's username to the global list
// echo to client they've connected
if(php.in_array(socket.username,usernames)){
delete usernames[socket.username];
}else{
usernames[user] = user;
console.log('not exist');
socket.emit('updatechat', 'SERVER', 'you have connected');
// echo globally (all clients) that a person has connected
socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
// update the list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
}
});
// when the user disconnects.. perform this
socket.on('disconnect', function(){
// remove the username from global usernames list
delete usernames[socket.username];
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
});
});
}
server.listen(3000);
例如,用户 master 将连接到我们的聊天室,他的用户名将存储在基于 php 的应用程序中。但是现在问题出在哪里?当用户 master 从我们浏览器的 2 或 3 选项卡连接时,他将连接到套接字服务器 3 或 4次,如果他发布一些数据,我们就会得到这个结果
master : hello
master : hello
master : hello
我希望用户只连接到我的应用程序一次,并且可以只发布一次数据。现在我应该如何实现呢?
如果互相私信,我应该如何访问这些用户
我是 node.js.my bad.sorry 的新手
提前感谢您的帮助。+1 所有老师