websocket问题:无法连接到node.js服务器 [英] websocket problem: cannot connect to node.js server
问题描述
我有一个node.js服务器启动并运行express,我试图建立一个使用socket.io服务器端和chrome 12客户端的websocket连接。当我尝试连接时,socket.io输出一条调试消息,说销毁nonsocket.io升级,并且我的连接处理程序中的代码无法运行。另外在客户端,我的套接字的readyState是2(CLOSING)。
readyState的套接字从0变为2 p>
请确保您将socket.io.js文件插入您的客户端代码并使用它。如果您尝试在客户端创建自己的websocket,您可能会遇到问题。
为您的服务器执行类似操作:
var app = require('express')。createServer()
,io = require('socket.io')。listen应用程序);
app.listen(80);
app.get('/',function(req,res){
res.sendfile(__ dirname +'/index.html');
});
io.sockets.on('connection',function(socket){
socket.emit('news',{hello:'world'});
socket。 on('my other event',function(data){
console.log(data);
});
});
类似于您正在提供的HTML文件:
< script src =/ socket.io/socket.io.js\"> ;</script>
< script>
var socket = io.connect('http:// localhost');
socket.on('news',function(data){
console.log(data);
socket.emit('my other event',{my:'data'}) ;
});
< / script>
请确定您正在服务 /socket.io/socket.io。 js
来自你的web服务器目录。然后,您所要做的就是在选项中或使用 Firebug 时,在控制台中登录Web浏览器的开发环境到页面。
I've got a node.js server up and running with express and i'm trying to establish a websocket connection using socket.io server-side and chrome 12 client-side. When I try to connect, socket.io outputs a debug message saying "destroying non-socket.io upgrade" and the code in my connection handler doesn't run. Also on the client-side the readyState of my socket is 2 (CLOSING).
[edit] readyState of the socket changed from 0 to 2
Make sure you're inserting the socket.io.js file into your client code and using it. If you try to create your own websocket on the client-side, you'll probably run into problems.
Do something like this for your server:
var app = require('express').createServer()
, io = require('socket.io').listen(app);
app.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
and something like this for the HTML file you're serving:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Make sure you're serving /socket.io/socket.io.js
from your webserver dir. Then all you have to do is watch your console log in the web browser's Developer environment from the Options or with Firebug when you go to the page.
这篇关于websocket问题:无法连接到node.js服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!