2016-09-17 33 views
2

我在Express服務器Socket.io socket.broadcast.to不工作

userbase = {'Fitz': '84Iw3MNEIMaed0GoAAAD'}; //Exapmle user to receive message and associated socket id 



//Sending message to Example user 
    socket.on('send_msg',function(data_from_client){ 



     //Testing for receivers socketId 


    console.log(userbase[data_from_client.to_user]);//This returns the socket id for Fitz in userbase successfully i.e 84Iw3MNEIMaed0GoAAAD 



     socket.broadcast.to(userbase[data_from_client.to_user]).emit('get_msg',{msg:data_server.msg}); 
    }); 

驚喜驚喜,當我安裝一個處理程序上我cliens側這一事件爲'get_msg'我什麼也得不到。

.factory('SocketFctry',function(){ 
    var socket = io('http://localhost:3002') 

    return socket; 
}) 



.controller('ChatCtrl', function($scope,SocketFctry) { 

SocketFctry.on('get_msg',function(received_message){ 
    console.log(received_message); 
    $scope.$apply(); 

}) 


}); 

我的其他客戶端處理程序工作正常。

SocketFctry.on('new_user', function(users,my_id){ 
    console.log(users); 
    $scope.online_users = users; 
    $scope.$apply(); 
    }) 

我的版本的socket.io是1.3.7。我在這裏丟失了什麼?

回答

0

你有沒有用戶加入連接的命名空間?

socket.join(userbase[data_from_client.to_user]); //'84Iw3MNEIMaed0GoAAAD' 

你可以試試:

socket.in(userbase[data_from_client.to_user]).emit('get_msg', {msg:data_server.msg}); 
+0

我unsderstand每個連接的客戶端會自動添加到房間與他的插座#ID ...您的解決方案使用'socket.in(socket.id)對我來說'工作,但我米仍然難倒'socket.broadcast.to(socket.id)'不起作用。我真的很想理解爲什麼在接受答案之前。任何想法? – yaboiduke

+0

看看這個http://stackoverflow.com/questions/6873607/socket-io-rooms-difference-between-broadcast-to-and-sockets-in#answer-6877212 – gyc

2

socket.broadcast().to()發送消息,以匹配to()參數除非誰的socket它是用戶的所有用戶。因此,socket.broadcast.to(socket.id)將永遠不會發送給實際的socket用戶。實際上,默認情況下,它不會發送給任何人。

從socket.io文檔直接:

播放,只需添加廣播標誌發出和發送方法 調用。廣播意味着向除了啓動它的套接字的 以外的其他人發送消息。

如果您要發送到只有一個插座,然後只需使用:

socket.emit(...) 

如果你想廣播到socket.id型房間,並要包含誰的房間用戶它,然後使用:

io.to('some room').emit('some event'): 

所以,你可以改變這一點:

socket.broadcast.to(userbase[data_from_client.to_user]).emit('get_msg',{msg:data_server.msg}); 

這樣:

io.to(userbase[data_from_client.to_user]).emit('get_msg',{msg:data_server.msg}); 
+0

你保存了一天兄弟..! !非常感謝..!! – Ritesh