2014-11-14 107 views
0

我在我的項目中使用了socket.io,並且無法向服務器發送數據,所以我設置了一個簡單的測試用例。我創建了一個文件,index.html這是我在谷歌瀏覽器已經打開(使用文件://地址):無法使用Socket.IO發送到節點服務器

<!DOCTYPE html> 
<html> 
    <head> 
     <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> 
     <script type="text/javascript"> 
      var socket = io('http://localhost:8080'); 
      socket.emit('clientDetails', {hello: 'world'}); 

      socket.on('connect', function() { 
       socket.emit('clientDetails', {hello: 'world'}); 
      }); 
     </script> 
    </head> 
    <body></body> 
</html> 

而且我有這個verys我的節點服務器上imple代碼:

var app = require('http').createServer(); 
var io = require('socket.io')(app); 

// Make the server listen on porr 8080 
app.listen(8080); 

io.on('connect', function(socket) { 
    console.log("Client connected"); 
}); 

io.on('clientDetails', function(socket) { 
    console.log("Got client details"); 
}); 

當我在Chrome中加載HTML頁面時,我得到一個由Node打印的Client connected消息。一切都很好。但我從來沒有看到一個Got client details字符串。

我懷疑有一些錯誤的服務器在尋找Chrome的網絡工具,我可以看到數據被髮送到服務器,至少我想這就是這是什麼:

enter image description here

爲什麼我我無法捕獲客戶端發送數據到服務器?

回答

1

Per the docs以下內容:

io.on('connect', function(socket) { 
    console.log("Client connected"); 
}); 

io.on('clientDetails', function(socket) { 
    console.log("Got client details"); 
}); 

應該

io.on('connect', function(socket) { 
    console.log("Client connected"); 

    socket.on('clientDetails', function(data) { 
     console.log("Got client details"); 
    }); 
}); 
相關問題