我是所有相关JavaScript programmimg的新手,我有一个使用nodejs和socket.io的应用程序完美地在本地(Mac)上工作。但是我无法弄清楚如何链接socket.io脚本并且不确定如何在运行的服务器(Hostgator专用运行的CentOS)中从应用程序连接到socket.io,我也在使用claudflare。
我尝试了几种组合:
的index.php
<script src="/socket.io/socket.io.js"></script>
//or also <script src="socket.io/socket.io.js"></script>
//console output is: Loading failed for the <script> with source “https://www.example.com/socket.io/socket.io.js”.
<script src="my_ip_number/socket.io/socket.io.js"></script>
//console output is: Loading failed for the <script> with source “https://www.example.com/my_ip_number/socket.io/socket.io.js”.
<script src="my_ip_number:8080/socket.io/socket.io.js"></script>
//console output is: Loading failed for the <script> with source “https://www.example.com/my_ip_number:8080/socket.io/socket.io.js”.
//the most odd one
<script src="https://my_ip_number/socket.io/socket.io.js"></script>
//console output is: Loading failed for the <script> with source “https://0.0.0/my_ip_number/socket.io/socket.io.js”.
app.js(客户端)
var socket = io.connect('my_ip_number:8080', { query: 'userid='+userOnline});
EDITED
如果我链接到CDN,我可以使脚本链接正常工作:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
这也与服务器版本相对应。在这种情况下,我将在控制台上收到以下错误:
client connect_error: Error: xhr poll error
Stack trace:
r.prototype.onError@https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js:2:7328
o.prototype.doPoll/<@https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js:2:1979
r.prototype.emit@https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js:1:12370
i.prototype.onError@https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js:2:3683
i.prototype.create/n.onreadystatechange/<@https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js:2:3309
server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
var http = require('http').Server(app);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
http.listen(8080, function(){
console.log('listening');
});
var io = require('socket.io').listen(http);
非常感谢任何帮助!