2017-08-09 109 views
1

我有我的虛擬服務器(Ubuntu的),它運行作爲一個systemd服務,這是積極地運行,創造了一個socket.io聊天應用從客戶機到服務器的連接。Socket.io - 通過https

我server.js位於:

/var/www/vhosts/mywebpage.de/w1.mywebpage.de/chat/ 

的server.js看起來是這樣的:

const io = require('socket.io')(3055); 

io.on('connection', function(socket) { 

    // When the client emits 'addUser', this listens and executes 
    socket.on('addUser', function(username, room) { 
     ... 
    }); 

    // When the client emits 'sendMessage', this listens and executes 
    socket.on('sendMessage', function(msg) { 
     ... 
    }); 

    // Disconnect the user 
    socket.on('disconnectUser', function(username, room) { 
     ... 
    }); 

}); 

在我的網站(HTTPS),我嘗試連接如下:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script> 

<script type="text/javascript"> 
    var loSocket; 
    $(document).ready(function() { 
     if(typeof(loSocket) == 'undefined') { 
      loSocket = io('https://w1.mywebpage.de:3055', { 
       reconnectionAttempts: 5, 
       forceNew: true 
      }); 
     } 
    }); 
</script> 

但我不能得到有效的連接。

開發工具這樣說:

(failed) ERR_CONNECTION_CLOSED with initiator polling-xhr.js:264. 

可能是什麼錯誤?

+0

好,socket.io是在其上沒有Web服務器,那麼你將使用節點http或expressjs在server.js需要安裝一個服務器。見https://socket.io/docs/ –

+0

但大約2年前,我得到了同樣的server.js工作。我不知道自那以後發生了什麼變化。 server.js使用/ usr/bin/node永久運行。 – Kelturio

回答

0

從我在過去所做的那樣我會創造一個https服務器供應的SSL證書,並使用您創建的HTTPS服務器上創建套接字服務器,這將允許您通過HTTPS連接,你將需要啓用secure在socketio(use this question as a ref

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

使用此代碼對如何使用http創建socketio服務器 您可以找到socket.io docs

注意此代碼REF:您需要將您https不是http類似的例子所示

+0

謝謝,但我不認爲那是問題,因爲你可以在中間從https://socket.io/docs/看到... VAR插座= 10(「socket.io」)(PORT)...已經創建了一個http服務器。 – Kelturio

+0

如果你不提供一個,那麼它會創建一個,如果你創建了自己的並使用它創建套接字服務器,它將使用你創建的套接字服務器。 – y0hami

+0

@Kelturio它創建_HTTP_服務器,而不是_HTTPS_服務器。 – robertklep