![](/img/trans.png)
[英]How to connect to tcp server via node.js/socket.io from client?
[英]Socket.io - Connect from client to server via https
我已經在虛擬服務器(Ubuntu)上創建了一個socket.io聊天應用程序,該應用程序作為systemd服務運行,並且正在運行。
我的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.
可能是什么錯誤?
從過去的工作來看,我將創建一個提供SSL證書的https服務器,並使用您創建的https服務器創建套接字服務器,這將允許您通過https進行連接,並且需要在socketio上啟用secure
性( 使用這個問題作為參考 )
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文檔中找到此代碼。
注意:您將需要https而不是HTTP,如示例中所示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.