node.jsとsocket.ioを使用してキー間のプライベートチャットを作成する質問する

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

ベストアンサー1

ルームを作成し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
});

サーバ

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

ルームの作成、ルームへの登録、ルームへのメッセージの送信に関するドキュメントと例は次のとおりです。

  1. Socket.ioルーム
  2. Socket.IO 複数のチャネルを購読する
  3. Socket.io ルーム、broadcast.to と sockets.in の違い

おすすめ記事