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

目前我得到了这个 SERVER 代码:

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');
});
  })

最佳答案

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

第二种方式是使用房间。每当客户端连接时,我想他有一个名字,例如约翰。然后你可以使用这样的东西来连接他:

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

现在这将创建一个房间并向其中添加 socket。如果您想向 John 发送消息,那么您只需使用
io.sockets.in('/priv/John').emit('msg', data);

此时,您可以确定消息完全发送到 /priv/John 房间中的套接字。这与 Redis 结合 socket.io(以避免许多机器问题)和 session 授权完美结合。我没有用 memoryStore 尝试它,但它应该也能工作。

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

关于node.js - 使用 php 的 Nodejs 私有(private)聊天,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9680200/

10-12 12:25
查看更多