Sockets are not working with CloudFlare (Solved by myself)
I have nodejs web socket server running on port 3000 on my Debian based VPS. I am currently using free plan of cloudflare.
socket.mydomain.com is gray record in CloudFlare and sockets are working with this URL but I don't want to work this way because I don't want to expose my server's IP address. Main problem is that sockets are not working on main orange record in cloudflare. Cloudflare have sockets support in free plan too but why these are not working? What I am doing wrong?
I have Laravel application and it was not working with Cloudflare initially and I had to install https://github.com/fideloper/TrustedProxy to work with cloudflare.
I tried to follow this guide but no luck: http://expressjs.com/en/guide/behind-proxies.html
I have been trying to solve this issue for weeks.
Here is the nodejs socket server codes:
var express = require('express');
var https = require('https');
var http = require('http');
var app = express();
var port = '3000';
//app.enable('trust proxy fn');
//app.set('trust proxy fn', 'loopback, linklocal, uniquelocal');
app.set('trust proxy fn', [
// Ipv4
'103.21.244.0/22',
'103.22.200.0/22',
'103.31.4.0/22',
'104.16.0.0/12',
'108.162.192.0/18',
'131.0.72.0/22',
'141.101.64.0/18',
'162.158.0.0/15',
'172.64.0.0/13',
'173.245.48.0/20',
'188.114.96.0/20',
'190.93.240.0/20',
'197.234.240.0/22',
'198.41.128.0/17',
'199.27.128.0/21',
// Ipv6
'2400:cb00::/32',
'2405:8100::/32',
'2405:b500::/32',
'2606:4700::/32',
'2803:f800::/32',
]);
var server = http.createServer(app);
var io = require('socket.io')(server);
var Redis = require('ioredis');
var redis = new Redis({password: "myredispassword"});
server.listen(port, function () {
var addr = server.address();
// console.log(addr);
console.log(' server listening on ' + addr.address + ':' + addr.port);
});
//function handler(req, res) {
// console.log(req);
// res.writeHead(200);
// res.end('');
//}
io.on('connection', function (socket, req) {
// console.log(socket);
// console.log(req);
});
redis.psubscribe('*', function (err, count) {
//
});
redis.on('pmessage', function (subscribed, channel, message) {
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.data);
});
Client-side code:
<script src="{{ asset('assets/js/socket.io.js') }}"></script>
// var socket = io('<?php echo url('/'); ?>:3000', {secure: false, port: 3000}); // does not work
var socket = io('socket.mydomain.com:3000', {secure: false, port: 3000}); // works but prone to DDoS
socket.on('test-event:App\\Events\\TestEvent', notifyUser_mine);
</script>
How did you solved it?
@alvaro210 I was using wrong port in Cloudflare. Only few ports are allowed in Cloudflare. I used 8443 after knowing allowed ports.
Cloudfare's allowed ports look to be fairly well documented online, for example, here (recent) or here (older).