我想有许多组用户之间的实时连接,我是新的服务器端脚本.........我想发送某些消息(数据)给某些用户,现在我的问题是如何做到这一点,无论是有一个相同的套接字所有用户或不同的套接字连接为不同的用户或不同的任务…?
目前我只是使用一个套接字并以这种方式为用户服务,这不是实际的应用程序,它只是我将要做的一个原型:
var io = require('socket.io').listen(server);
server.listen(http_port);
var allUsers=[];
var num=1;
io.sockets.on('connection', function (socket) {
var user = 'user#'+num++;
allUsers[user] = socket;
socket.on('message',function(data){
if(data.to)
allUsers[data.to].emit("message",{msg:data.msg,by:data.by});
});
});
客户端:
socket.emit('message',{to:'user#1',from:'talha',msg:'hello'});
Maybe, I am on a wrong approach, becuase later on I will be quering to database sending those results to specific clients, how do i manage that.
Please provide some code details along with your anwers .. Thanks in advance. No, you only have one listening socket. On each connection (as it can be seen from io.sockets.on('connection', function(socket){..
) , your function(socket){....}
is called and the socket in that function is identical to each connection/user. The function callbacks on "connection"
event are sepearate and one for each user.
EDIT: For user seperating users you can do the following:
var users = [];
io.sockets.on("connection", function(socket){
socket.on("message", function(data){
// Handle if it is a valid user, make some authentication and have a username..
users[username] = socket;
// on another message, if you want to send message
users["myuser"].send(...)
}
});