gag*_*ina 15 sockets node.js socket.io
我正在尝试使用socket.io和node.js.
在socket.io的网站上的第一个例子后,我在浏览器的控制台中收到以下错误:
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
Run Code Online (Sandbox Code Playgroud)
这是我的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);
});
});
Run Code Online (Sandbox Code Playgroud)
这是我的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>
Run Code Online (Sandbox Code Playgroud)
我已经安装了socket.io ..
Mic*_*ets 25
首先,您需要查看服务器app.listen(3001);
在客户端绑定的服务器端口()以便完全到达服务器.
至于socket.io,http://localhost:3001
在链接标记中的其余源代码之前添加解决了这个问题.这显然是由于网络将端口绑定到localhost的方式,但是我会尝试找到有关原因的更多信息;
服务器的端口绑定:
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>
如果您使用的是express
版本3.x,则存在Socket.IO兼容性问题,需要进行一些微调才能进行迁移:
Socket.IO的
.listen()
方法将http.Server
实例作为参数.
从3.x开始,返回值express()
不是http.Server
实例.要使Socket.IO与Express 3.x一起使用,请确保手动创建并将您的http.Server
实例传递给Socket.IO的.listen()
方法.
这是一个简单的例子:
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(3000);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
40175 次 |
最近记录: |