A
A
Alexander Alexandrovich2016-10-13 20:26:21
Node.js
Alexander Alexandrovich, 2016-10-13 20:26:21

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

This is used next:
io.sockets.on('connection', function (client) {
...... и т.д. .......

On the client, socket.io is connected like this:
<script type="text/javascript" src="//mysite.ru:8010/socket.io/socket.io.js"></script>

How can I change this connection so that it works on both http and https? Google is already saying hello to me, Yandex thinks that I am a bot and displays captcha. So I didn't find an answer. There are some specific manuals but I could not connect.
It costs nginx, certificates for the site on nginx are installed. The site works on https, but socket.io and node.js did not master the connection.
I read both the official documentation and user solutions, but they all have a slightly different connection solution, which I could not apply to my version.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
de1m, 2016-10-14
@kreatorBB

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

On the client side, you need to add an http or https check.
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 question

Ask a Question

731 491 924 answers to any question