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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With