Skip to content

Instantly share code, notes, and snippets.

@dazzz1er
Last active August 23, 2021 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dazzz1er/47fc5a5025838ac7276e to your computer and use it in GitHub Desktop.
Save dazzz1er/47fc5a5025838ac7276e to your computer and use it in GitHub Desktop.
Socket.io, Redis implementation
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script>
var socket = io('http://localhost:3000');
socket.on('test-channel:Test', function(message) {
console.log(message); // Object { user : 'danje', status : 'awesome' }
});
</script>
<?php
use Redis;
class Broadcaster {
public function broadcastRedisEventToSocketIO()
{
$connection = Redis::connection('default'); // note that Redis may have to be given a new alias in app/config if php redis module is enabled
$event = 'Test';
$payload = json_encode(['event' => $event, 'payload' => ['user' => 'danje', 'status' => 'awesome']]);
$connection->publish('test-channel', $payload);
}
}
?>
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis(6379, '192.168.10.10');
redis.subscribe('test-channel', function(err, count) {
//
});
io.on('connection', function(socket) {
console.log('a user connected');
});
//io.set('transports',['xhr-polling','jsonp-polling']); apply this if websocket is failing to connect on modern browsers
redis.on('message', function(channel, message) {
console.log('Message received!');
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.payload);
});
http.listen(3000, function() {
console.log('Listening on *:3000');
});
@dazzz1er
Copy link
Author

dazzz1er commented May 8, 2015

The example implementation with the three files runs as-is using Laravel homestead configured to 192.168.10.10 as it comes with Redis out of the box.

Node.JS is required to run the socket.js server file and naturally express, socket.io and ioredis need to be pulled in for the server to work.

@shoemoney
Copy link

shoemoney commented Aug 23, 2021

Love redis pub/sub. Check out the nchan mod that ships with nginx you can create endpoints that link to sub models it's great. For instance if you had a crypto exchange you can have an endpoint of /btcusd /ethusdt etc works really well and goes through redis so it scales amazing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment