2012-04-21 98 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

相关问题