Answer the question
In order to leave comments, you need to log in
How to formulate a socket.io connection over https and http using an example?
There is a connection like this:
var PORT = 8010;
var options = {
'authorization': isAuth
};
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server, options);
server.listen(PORT);
io.sockets.on('connection', function (client) {
...... и т.д. .......
<script type="text/javascript" src="//mysite.ru:8010/socket.io/socket.io.js"></script>
Answer the question
In order to leave comments, you need to log in
It will not work on one port, two ports are needed.
I changed the example, but this one definitely works for me, on only two ports
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var fs = require('fs');
var https = require('https');
app.set('views', __dirname + '/views')
app.set('view engine', 'pug')
app.use(express.static(__dirname + '/public'))
server.listen(5000, function () {
console.log('Server listening at port %d', 5000);
});
const opts = {
key: fs.readFileSync('privateKey.key'),
cert: fs.readFileSync('certificate.crt')
}
var httpsServer = https.createServer(opts, app);
httpsServer.listen(5001, function(){
console.log("HTTPS on port " + 5001);
})
app.get('/', function (req, res) {
res.render('index');
})
io.attach(httpsServer);
io.attach(server);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('click', function(data){
console.log(JSON.parse(data));
setTimeout(function() {
client.emit("ok", "data");
}, 3000);
})
});
if (window.location.protocol != "https:"){
var socket = io.connect('https://localhost:5001');
} else {
var socket = io.connect('http://localhost:5000');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question