[英]Issues with using Socket.io
I am trying to use socket.io for the first time, Im using it with a MEAN Stack. 我试图第一次使用socket.io,我将它与MEAN Stack一起使用。 I have set it up the following way.
我通过以下方式进行设置。
Server.js Server.js
var express = require('express');
var app = express(); // create our app w/ express
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.listen(port);
io.on('connection', function(socket) {
socket.emit('message', {
'message': 'hello world'
});
});
HTML File HTML文件
<script>
var socket = io.connect();
socket.on('message', function(data) {
console.log(data.message);
});
</script>
I couldn't find the socket.io.js
file so I searched for a CDN for the script. 我找不到
socket.io.js
文件,所以我在CDN中搜索了该脚本。 I used the following. 我使用了以下内容。
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.6/socket.io.js"></script>
I tried downloading the socket.io.js from their website but the website seems to be down. 我尝试从他们的网站下载socket.io.js,但该网站似乎已关闭。 I can access it, I get the 502 BAD GATEWAY error ( http://socket.io )
我可以访问它,但收到502 BAD GATEWAY错误( http://socket.io )
When I load my HTML page after setting everything up as shown above I get the following error in the console. 如上所示,在完成所有设置后加载HTML页面时,在控制台中出现以下错误。
Any help will be greatly appreciated! 任何帮助将不胜感激!
UPDATE: 更新:
The socket.io
server will perform some magic to provide that file when you retrieve it like this: 当您按以下方式检索文件时,
socket.io
服务器将执行一些魔术操作以提供该文件:
<script src="/socket.io/socket.io.js"></script>
EDIT : ah, I see the problem: your Express setup is incorrect. 编辑 :啊,我看到了问题:您的Express设置不正确。
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.listen(port);
You're attaching socket.io
to a server created by http.createServer
, but with app.listen()
you're actually creating a new server, one that socket.io
isn't attached to. 您正在将
socket.io
附加到由http.createServer
创建的服务器上,但是实际上是使用app.listen()
创建了一个新服务器,没有连接socket.io
服务器。
You can make the setup a bit simpler: 您可以使设置更简单:
var express = require('express');
var app = express();
var server = app.listen(port);
var io = require('socket.io')(server);
No need to use http
. 无需使用
http
。
As of now, socket.io website is still down. 截至目前,socket.io网站仍处于关闭状态。 If you don't have the file in your server, it does not help using
/socket.io/
because this points to a route on your server and that route doesn't seem to exist on your app. 如果服务器中没有该文件,则使用
/socket.io/
将/socket.io/
因为它指向服务器上的路由,并且该路由似乎在您的应用中不存在。 With this config, you need to be serving the .js file statically from your server - but I don't see that on your server code. 使用此配置,您需要从服务器静态提供.js文件-但我在服务器代码上看不到该文件。
When you try the CDN, make sure the file is being loaded. 当您尝试CDN时,请确保正在加载文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.