Asa*_*ter 24 javascript chat node.js socket.io
如何使用node.js和socket.io向共享conversation_id的私人聊天中的所有用户发送消息?
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
conversations = {};
app.get('/', function(req, res) {
res.sendfile('/');
});
io.sockets.on('connection', function (socket) {
socket.on('send message', function (data) {
var conversation_id = data.conversation_id;
if (conversation_id in conversations) {
console.log (conversation_id + ' is already in the conversations object');
// emit the message [data.message] to all connected users in the conversation
} else {
socket.conversation_id = data;
conversations[socket.conversation_id] = socket;
conversations[conversation_id] = data.conversation_id;
console.log ('adding ' + conversation_id + ' to conversations.');
// emit the message [data.message] to all connected users in the conversation
}
})
});
server.listen(8080);
Run Code Online (Sandbox Code Playgroud)
Sri*_*eva 55
您必须创建一个房间conversation_id并让用户订阅该房间,以便您可以向该房间发出私人消息,
客户
var socket = io.connect('http://ip:port');
socket.emit('subscribe', conversation_id);
socket.emit('send message', {
room: conversation_id,
message: "Some message"
});
socket.on('conversation private post', function(data) {
//display data.message
});
Run Code Online (Sandbox Code Playgroud)
服务器
socket.on('subscribe', function(room) {
console.log('joining room', room);
socket.join(room);
});
socket.on('send message', function(data) {
console.log('sending room post', data.room);
socket.broadcast.to(data.room).emit('conversation private post', {
message: data.message
});
});
Run Code Online (Sandbox Code Playgroud)
以下是创建房间,订阅房间和向房间发送消息的文档和示例:
Tro*_*jan 15
当然:简单地说,
这就是你需要的:
io.to(socket.id).emit("event", data);
Run Code Online (Sandbox Code Playgroud)
每当用户加入服务器时,将生成包括ID的套接字详细信息.这是真正有助于向特定人员发送消息的ID.
首先我们需要将所有socket.id存储在数组中,
var people={};
people[name] = socket.id;
Run Code Online (Sandbox Code Playgroud)
这里的名字是收件人姓名.例:
people["ccccc"]=2387423cjhgfwerwer23;
Run Code Online (Sandbox Code Playgroud)
所以,现在我们可以在发送消息时使用接收者名称获取socket.id:
为此我们需要知道recievername.You需要向服务器发出接收者名称.
最后一件事是:
socket.on('chat message', function(data){
io.to(people[data.reciever]).emit('chat message', data.msg);
});
Run Code Online (Sandbox Code Playgroud)
希望这对你有用.!!祝你好运
| 归档时间: |
|
| 查看次数: |
36128 次 |
| 最近记录: |