Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use both http and https for socket.io

I am trying to make socket.io work both on http and https connections, but it seems that with my current configuration it can work only on one of them.

With the below config options it can access my application through https, but when trying to access it through http it cannot connect and I receive errors:

    var app = express()
  , http= require('http').createServer(app)
  , https = require('https').createServer(options, app)
  , io = require('socket.io').listen(https, { log: false })

And later I have this:

http.listen(80, serverAddress);
https.listen(443, serverAddress);

On client side I have this:

<script src='/socket.io/socket.io.js'></script>

var socket = io.connect('https://<%= serverAddress %>', {secure: true, 'sync disconnect on unload' : true});

Of course if I switch the http with the https options on the .listen and .connect functions of the server and the client respectively I am having the reverse results, e.g. it can access through http and not through https.

How is it possible to achieve this? I need it mostly because it is regarding a Facebook app, so it must provide both http and https connection options according to Facebook's rules.

Edit: In case it helps about the problem, the error I am receiving is this:

Failed to load resource: the server responded with a status of 404 (Not Found) http://DOMAIN/socket.io/socket.io.js

And because of this I get others such as:

Uncaught ReferenceError: io is not defined 
like image 524
Vassilis Barzokas Avatar asked Jun 24 '13 21:06

Vassilis Barzokas


People also ask

Does Socket.IO need HTTP?

Websocket is created when you make upgrade from http to websocket, so it kind of does need http. socket.io isn't a pure Websocket server/implementation, it depends on HTTP for its initial connection setup.

Does Socket.IO use https?

If you want socket.io to use https, just pass a key param to the listen() function. You can also run your server behind stunnel.

Is Socket.IO full duplex?

info. WebSocket is a communication protocol which provides a full-duplex and low-latency channel between the server and the browser. More information can be found here.


1 Answers

I have done something similar and it required two socket.io instances. Something like this:

var express = require('express');
var oneServer = express.createServer();
var anotherServer = express.createServer();
var io = require('socket.io');

var oneIo = io.listen(oneServer);
var anotherIo = io.listen(anotherServer);

Of course that you will need to inject messages twice: for both socket.io instances.

A good option is delegate SSL handling to stunnel and forget about SSL in your code.

like image 72
MrTorture Avatar answered Oct 11 '22 12:10

MrTorture