2012-04-21 148 views
0

我在我的智慧'結束在這裏,所以任何幫助將非常感激。不能發送/從客戶端發送到NodeJS服務器使用sockets.io

我想通過socket.io發送或從我的客戶端(網頁)發送消息到我的Node.JS服務器。這是在作爲本地主機運行的Windows 7上。

確切的問題是:

  • 我可以從服務器發送信息到客戶端就好了。
  • 從客戶端發送消息到服務器不工作:(

Server代碼:

// create http server 
var app = require('http').createServer(httpHandler); 
// socket.io 
var io = require('socket.io').listen(app); 

var port = 8080; 

app.listen(port); 
console.log('Server running at http://127.0.0.1:' + port); 

// socket connection handler 
io.sockets.on('connection', function (client) { 
    // this works great:  
    client.emit('text_msg', {msg: 'Welcome you are now connected.'}); 

    // plain message - this never works :(
    io.sockets.on('message', function(data){ 
     console.log("*************************** message : " + data.txt); 
    }); 
}); 

下面是一些客戶端代碼:

<script src="/socket.io/socket.io.js"></script> 

...snip... 

var socket = io.connect('http://localhost'); 
socket.emit('message', {txt:"test"}); 

socket.on('text_msg', function (data) { 
    alert(data.msg); 
}); 

我已經嘗試了以下瀏覽器:

  • 的Chrome 18(Windows 7)中
  • 的Firefox 11(Windows 7)中
  • 的Internet Explorer 9(Windows 7)中

從的NodeJS輸出,我可以同時看到Chrome和Firefox使用WebSockets和IE9使用「 HTMLFILE」。

是的NodeJS版本0.6.15

NPM名單看起來像:

├── [email protected] 
└─┬ [email protected] 
    ├── [email protected] 
    ├── [email protected] 
    └─┬ [email protected] 
    ├─┬ [email protected] 
    │ └── [email protected] 
    ├── [email protected] 
    ├─┬ [email protected] 
    │ ├── [email protected] 
    │ └── [email protected] 
    └── [email protected] 

感謝您的任何援助。

+0

爲了清楚起見,從客戶端,我收到來自服務器的消息,並且它在警報框中可見。 – JimFing 2012-04-21 13:39:37

回答

2

變化:

io.sockets.on('message', function(data){ 
console.log("*************************** message : " + data.txt); 
}); 

要:

client.on('message', function(data){ 
console.log("*************************** message : " + data.txt); 
}); 

當你調用

io.sockets.on('connection', function (client) 

您所定義的 「客戶」,這是插座當前命名空間THA客戶端正在發射。

+0

謝謝!不能相信我沒有發現。 – JimFing 2012-04-22 08:35:42

相關問題