私は現在socket.ioと簡単なチャットをしています。基本はすでに動作していますが、今は2つの異なる名前空間を実装しようとしています。私は、クライアントがボタンクリックで1つの名前空間(サポートチャット)から他の(フレンドチャット)に切り替えることができるようにしたい。socket.io名前空間を切り替える
サーバーサイド
//default namespace
io.on('connection', function(socket){
console.log('a user connected to the chat');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('client message', function(msg){
io.emit('server_message', msg);
});
});
//namespace /support
var sup = io.of('/support');
sup.on('connection', function(socket){
console.log('someone entered the support-chat');
socket.on('disconnect', function(){
console.log('user disconnected from support-chat');
});
//recieving and emitting message to all clients in namespace /support
socket.on('client message', function(msg){
console.log('message received: ' + msg);
io.of('/support').emit('server_message', msg);
});
});
//namespace /friends
var frnd = io.of('/friends');
frnd.on('connection', function(socket){
console.log('someone entered the friends-chat');
socket.on('disconnect', function(){
console.log('user disconnected from friends-chat');
});
//recieving and emitting message to all clients in namespace /friends
socket.on('client message', function(msg){
console.log('message received: ' + msg);
io.of('/friends').emit('server_message', msg);
});
});
クライアント側
var socket = io.connect();
//toggle namespace
$("#support_button").click(function(){
socket.disconnect();
socket = io('/support');
$('#messages').append($('<li>').text("You entered the Support-Chat"));
});
//toggle namespace
$("#friends_button").click(function(){
socket.disconnect();
socket = io('/friends');
$('#messages').append($('<li>').text("You entered the Friends-Chat"));
});
//sending message on submit
$('form').submit(function(){
socket.emit('client message', $('#m').val());
$('#m').val('');
return false;
});
//recieving message and display
socket.on('server_message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
彼らが必要のようconnection-と切り離し、イベントがトリガされているので、私は、スイッチ自体が機能していると思います。しかし、同じ名前空間の全員にメッセージ(クライアントから受信したサーバー)を送信することになると、それは機能しません。
ありえないこの特定の名前空間に放出するためのserversidedコール?:
io.of('namespace').emit();
は私が名前空間の使用法を誤解していますか?私は、サポートと友人のための2つのメインチャットの名前空間 - 「分割」の直後に部屋を実装したかったのです。 または、サーバー側で間違った名前空間を実装しましたか?私はio.on(..)、io.of( '/ support')とon(..)とio.of( '/ friends')のon ..(..)はすべて同じ方法で動作し、独自のネームスペースのイベント - クライアント。
ご協力いただきありがとうございます。私は、名前空間が「基本的な使用法」の文書で無視されているように感じます。
これはすばらしい答えであり、正確に私が知る必要があったものです!どうもありがとう! – ExaMa