我正在使用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");
});
});
当我运行它时,它会生成以下网址: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.
注意:当我在本地托管服务器时,它可以完美运行。
看起来像 c9.io 使用代理或防火墙,但我如何远程测试在 c9.io 中编写的代码?
更新
根据 ruben 的回复,我已经更改了我的服务器,当我的 socket.io-client 托管在 C9 中时它可以工作,但仍然无法在远程客户端上运行(我也在我的 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);
});
});
看起来原始配置已被忽略,我也不确定 C9.io..
建议?
干杯。
最佳答案
您正在使用端口 8080。请尝试使用 process.env.IP
和 process.env.PORT
。此外,不要指定域上的端口到您的工作区,这一点很重要。默认端口(端口 80)转发到 c9.io
上容器的内部端口。如果您通过不指定的方式连接到默认端口,则不会出现跨域安全问题。
另请参阅: https://c9.io/site/blog/2013/05/native-websockets-support/
Ruben - Cloud9 支持
关于node.js - 如何连接到远程 Node.js 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24897396/