2012-03-13 110 views
3

我想使用php在nodeJs + MYSQL中构建一个聊天系统。这将是一对一的私人聊天,并将在数据库中保存聊天。任何人都知道我需要从哪里开始。Nodejs使用php的私人聊天

目前我得到的服务器验证码:

var app = require('express').createServer() 
var io = require('socket.io').listen(app); 

app.listen(8181); 

// routing 
app.get('/', function (req, res) { 
res.sendfile(__dirname + '/index.html'); 
}); 

// usernames which are currently connected to the chat 
var usernames = {}; 

io.sockets.on('connection', function (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 = username; 
    // add the client's username to the global list 
    usernames[username] = username; 
    // echo to client they've connected 
    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'); 
}); 
    }) 
+0

你究竟需要什么?你已经知道如何编写一个服务器。你在实现客户端方面有问题吗? – freakish 2012-03-13 07:59:30

+0

感谢feakish参与,我可以建立服务器,作为初学者我很困惑如何使客户端服务器通信实现私人聊天,因为连接正在向所有客户端广播消息。 – 2012-03-13 08:04:31

回答

4

有两种方法。渴望持有对数组中所有套接字的引用(至少都是这些套接字的ID)。当用户发出私人消息时,您会搜索阵列中的目标套接字并将其发送给此特定套接字。这需要保存某种套接字的ID。您可以使用内部socket.id,但当客户端重新连接时(新生成的ID),将会出现问题。而当你的应用在多台机器上工作时(他们不能共享连接客户机的阵列),还有另一个问题。

第二种方法是使用房间。每当客户连接,我想他有一个名字,例如约翰。然后你可以使用这样的事情对他的连接:

socket.join('/priv/'+name); 

现在,这创造了一个房间,并增加了socket它。如果你想发送消息给约翰,你只需使用

io.sockets.in('/priv/John').emit('msg', data); 

在这一点上,你可以肯定的是,消息正好去到插座中/priv/John房间。这与Redis结合socket.io(以避免许多机器问题)和会话授权完美配合。我没有用memoryStore尝试它,但它应该也可以。

当客户断开连接时,您也不用担心房间。 Socket.io会自动销毁空房间。