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

时间:2014-07-22 20:40:40

标签: node.js socket.io

我正在使用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并告诉我我的代码正在此网址中运行。

注意: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中托管但仍无法在远程客户端上运行时,它可以正常工作(i&#39 ; ve还在我的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 ..

建议?

干杯。

2 个答案:

答案 0 :(得分:2)

Same-origin policy要求您的客户端代码和WebSocket服务器托管在相同的URL和端口上。您可以找到将它们集成到Socket.IO docs中的方法的具体示例。以下是使用内置HTTP服务器进行操作的示例。而不是给Socket.IO一个主机名/端口,你给它你的webserver对象:

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);
  });
});

答案 1 :(得分:2)

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

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

Ruben - Cloud9支持

相关问题