ソケットIOで特定のクライアントにメッセージを送信する 質問する

ソケットIOで特定のクライアントにメッセージを送信する 質問する

私は Socket IO v1.4.5 を使用しており、以下の 3 つの異なる方法を試しましたが、結果は得られませんでした。

client.emit('test', 'hahahaha');
io.sockets.socket(id).emit('test',''hahaha); 
io.sockets.connected[id].emit('test','hahaha');

これが私のサーバー側です

var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );
var dateFormat = require('date-format');
var app = express();
var server = http.createServer( app );
var io = socket.listen( server );
io.sockets.on( 'connection', function( client ) {
    user[client.id]=client;

//when we receive message 
    client.on('message', function( data ) {
        console.log( 'Message received from' + data.name + ":" + data.message +' avatar' +data.avatar );
        client.emit('test', 'hahahaha');
});

どんな助けでも大歓迎です。ご協力ありがとうございます。よろしくお願いいたします

ベストアンサー1

特定のクライアントにメッセージを送信するには、次のようにします。

socket.broadcast.to(socketid).emit('message', 'for your eyes only');

ソケットに関する便利なチートシートを以下に示します。

 // sending to sender-client only
 socket.emit('message', "this is a test");

 // sending to all clients, include sender
 io.emit('message', "this is a test");

 // sending to all clients except sender
 socket.broadcast.emit('message', "this is a test");

 // sending to all clients in 'game' room(channel) except sender
 socket.broadcast.to('game').emit('message', 'nice game');

 // sending to all clients in 'game' room(channel), include sender
 io.in('game').emit('message', 'cool game');

 // sending to sender client, only if they are in 'game' room(channel)
 socket.to('game').emit('message', 'enjoy the game');

 // sending to all clients in namespace 'myNamespace', include sender
 io.of('myNamespace').emit('message', 'gg');

 // sending to individual socketid
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');

クレジットhttps://stackoverflow.com/a/10099325


ソケットに直接送信するよりも簡単な方法は、2 人のユーザーが使用できる部屋を作成し、そこに自由にメッセージを送信することです。

socket.join('some-unique-room-name'); // Do this for both users you want to chat with each other
socket.broadcast.to('the-unique-room-name').emit('message', 'blah'); // Send a message to the chat room.

そうしないと、個々のクライアントのソケット接続を追跡する必要があり、チャットをしたいときにはそのソケット接続を検索し、上で述べた関数を使用してそのソケットに具体的に送信する必要があります。ルームの方がおそらく簡単です。

おすすめ記事