2013-08-12 96 views
2

我有以下代碼:Socket.io廣播不能正常工作

var room = "1"; 
var chat = io.connect("localhost:3700/"); 
    self.chat = chat; 
    chat.on("connection", function(socket){ 
     socket.emit("room", room); 
     socket.on('message', function (data) { 
      self.receiveMessage(data); 
     }); 
    }); 

chat.broadcast.to(room).emit('send',"HEllo"); 

receiveMessage:

receiveMessage: function(data){ 

     var $elem = $("#chat1"); 
     var $content = $elem.find(".messageText"); 
     if(data.message) { 
      messages.push(data); 
      var html = ''; 
      for(var i=0; i<messages.length; i++) { 
       html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>'; 
       html += messages[i].message + '<br />'; 
      } 
      $content.html(html); 
     } else { 
      console.log("There is a problem:", data); 
     } 
    } 

chat.broadcast.to(room).emit('send',"HEllo");給我的錯誤:

Uncaught TypeError: Cannot call method 'to' of undefined

我是什麼做錯了?

回答

3

不太確定,但我認爲你只能通過連接發送廣播。

你可以試試這個:

var room = "1"; 
var chat = io.connect("localhost:3700/"); 
    self.chat = chat; 
    chat.on("connection", function(socket){ 
     socket.emit("room", room); 
     socket.on('message', function (data) { 
      self.receiveMessage(data); 
     }); 


     chat.broadcast.to(room).emit('send',"HEllo"); 
    }); 

當然,你也可以發送廣播在一個單獨的處理程序,即:

var room = "1"; 
var chat = io.connect("localhost:3700/"); 
    self.chat = chat; 
    chat.on("connection", function(socket){ 
     socket.emit("room", room); 
     socket.on('message', function (data) { 
      self.receiveMessage(data); 
     }); 

     socket.on('foo event', function(data) { 
      chat.broadcast.to(room).emit('send',"HEllo"); 
     } 
    }); 
+0

我怎麼然後調用'富event'編程?我對套接字很陌生,所以有點困惑;) – rickyduck

+0

而實際上''連接'功能從來沒有觸發 – rickyduck

+1

@rickyduck socket.emit('foo event',data);將調用'foo事件'。 – sachin