2014-07-22 24 views
2

我使用C9.io如何連接到遠程Node.js服務器?

這裏我的服務器:

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/」 ....

然後我得到的控制檯(火狐瀏覽器)這個錯誤:

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遠程?

UPDATE

據魯本的迴應,我已經改變了我的服務器,它工作時,我的socket.io客戶端託管在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 ..

建議?

乾杯。

回答

2

您正在使用8080端口使用process.env.IPprocess.env.PORT而是嘗試。另外,不要在工作區中指定域上的端口。默認端口(端口80)將轉發到您的容器的內部端口c9.io。如果您通過不指定它來連接到默認端口,則不會出現跨域安全問題。

參見: https://c9.io/site/blog/2013/05/native-websockets-support/

魯本 - CLOUD9支持

+0

感謝Ruben,現在我的客戶端代碼在c9中工作,但仍然在遠程訪問中出現「跨源請求被阻止」,請參閱我的更新 –

2

Same-origin policy要求您的客戶端代碼和WebSocket服務器託管在相同的URL和端口上。你可以找到將它們整合到Socket.IO docs中的具體示例。以下是他們如何使用內置的HTTP服務器來做到這一點的例子。而不是給Socket.IO主機名/端口,你給它你的服務器對象:

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

感謝克里斯,你能提供給我一個鏈接到醫生,我無法找到我尋找.. –

+0

什麼Web服務器你正在用嗎? – Chris

+0

請參閱我的更新克里斯。 –