socket.io:无法加载资源 [英] socket.io: Failed to load resource
问题描述
我正在尝试使用socket.io和node.js.
I'm trying to getting started with socket.io and node.js.
按照socket.io网站上的第一个示例,我在浏览器的控制台中遇到以下错误:
Following the first example on the socket.io's site I'm getting the following error in the browser's console:
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3001/socket.io/socket.io.js
Uncaught ReferenceError: io is not defined
这是我的server.js
This is my server.js
var app = require('express').createServer()
, io = require('socket.io').listen(app);
app.listen(3001);
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);
});
});
这是我的index.html
And this is my index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8" />
</head>
<body>
<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>
</body>
</html>
我已经安装了socket.io.
I've already installed socket.io..
推荐答案
问题
-
首先,您需要查看服务器绑定到客户端的服务器端口(
app.listen(3001);
),以便完全到达服务器.The Issues
First of all you need to be looking at the server port that the server is bound on (
app.listen(3001);
) on the client side in order to reach the server at all.对于socket.io,在链接标记中的其余源代码之前添加
http://localhost:3001
可解决此问题.显然,这是由于网络将端口绑定到localhost的方式引起的,但是我将尝试查找有关此原因的更多信息;As for socket.io, adding
http://localhost:3001
before the rest of the source in the link tag solves this problem. This is apparently due to the way the network binds ports to localhost, however I will try to find some more information on the cause;服务器的端口绑定:
var socket = io.connect('http://localhost');
应更改为
var socket = io.connect('http://localhost:3001');
使socket.io表现为:
<script src="/socket.io/socket.io.js"></script>
应更改为
<script src="http://localhost:3001/socket.io/socket.io.js"></script>
这篇关于socket.io:无法加载资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!