如何连接到远程Node.js服务器?

我正在使用C9.io

这里我的服务器:

var io = require('socket.io'); var socket = io.listen(8080, { /* options */ }); socket.set('log level', 1); socket.on('connection', function(socket) { console.log("connected"); socket.on('message1', function(data) { socket.emit("message1",JSON.stringify({type:'type1',message: 'messageContent'})); }); socket.on('disconnect', function() { console.log("diconnected"); }); }); 

当我运行它产生这个url: https : //xxx-c9-smartytwiti.c9.io并告诉我,我的代码在这个URL中运行。

注意 :xxx是我的工作区

我在我的客户端做了什么:连接到“ https://xxx-c9-smartytwiti.c9.io:8080/ ”….

然后,我在控制台(Firefox浏览器)得到这个错误:

 cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxx-c9-smartytwiti.c9.io:8080/socket.io/1/?t=1406060495041. This can be fixed by moving the resource to the same domain or enabling CORS. 

注意 :当我托pipe我的服务器本地,它完美的作品。

看起来像c9.io使用代理或防火墙,但我怎样才能testing我的代码写在c9.io远程?

UPDATE

根据ruben的回应,我改变了我的服务器,当我的socket.io客户端在C9托pipe,但仍然无法在远程客户端上工作(我也托pipe客户端在我的FTP,但相同的结果) :

 // module dependencies var http = require("http"), sio = require("socket.io"); // create http server var server = http.createServer().listen(process.env.PORT, process.env.IP), // create socket server io = sio.listen(server); // set socket.io debugging io.set('log level', 1); io.set('origins', '*:*'); io.sockets.on('connection', function (socket) { socket.emit('news', { message: 'Hello world!' }); socket.on('my other event', function (data) { console.log(data.message); }); }); 

看起来像起源configuration已被忽略,我也不知道C9.io ..

build议?

干杯。

您正在使用端口8080.请尝试使用process.env.IPprocess.env.PORT 。 另外,不要在工作区中指定域上的端口。 默认端口(端口80)将转发到c9.io上的容器的内部端口。 如果您通过不指定它连接到默认端口,则不会遇到跨域安全问题。

另见: https : //c9.io/site/blog/2013/05/native-websockets-support/

Ruben – Cloud9支持

同源策略要求您的客户端代码和WebSocket服务器托pipe在相同的URL和端口上。 您可以find将它们集成到Socket.IO文档中的具体示例。 这里是他们如何使用内置的HTTP服务器来做的例子。 而不是给Socket.IO一个主机名/端口,而是给它你的networking服务器对象:

 var app = require('http').createServer(handler) var io = require('socket.io')(app); var fs = require('fs'); app.listen(80); function handler (req, res) { fs.readFile(__dirname + '/index.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); } io.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); });