Skip to content

Instantly share code, notes, and snippets.

@aronduby
Created November 14, 2018 07:09
Show Gist options
  • Save aronduby/9a3db9c857ceec660cd6b3f092349ff1 to your computer and use it in GitHub Desktop.
Save aronduby/9a3db9c857ceec660cd6b3f092349ff1 to your computer and use it in GitHub Desktop.
PHP/Node/Redis/Socket.IO
<?php
// require autoload
/*
* Setup Redis for PubSub for events
*/
$redis = new Predis\Client();
$pub = new Publisher($redis, 'pintourny', $subdomain);
$pub->send('event.type', $someData);
// this is the file in it's entirity, it just echos from the php publisher
var redis = require("redis"),
listener = redis.createClient(),
io = require('socket.io').listen(773,{
'close timeout': 3600, // 60 minutes to re-open a closed connection
'browser client minification': true,
'browser client etag': true,
'browser client gzip': true
});
io.sockets.on('connection', function(socket){
var domain = socket.handshake.headers.host,
sub_domain = domain.split('.').shift();
socket.join(sub_domain);
});
listener.on('message', function(channel, evt){
evt = JSON.parse(evt);
var type = evt.type,
data = evt.data,
room = evt.room;
io.to(room).emit(type, data);
});
listener.subscribe('pintourny');
<?php
class Publisher {
public $pub;
public $channel;
public $room;
public function __construct($pub, $channel, $room){
if(!method_exists($pub, 'publish'))
throw new InvalidArgumentException('Pub must be an object with a publish method');
$this->pub = $pub;
$this->channel = $channel;
$this->room = $room;
}
public function send($type, $msg){
$evt = new StdClass();
$evt->room = $this->room;
$evt->type = $type;
$evt->data = $msg;
return $this->pub->publish($this->channel, json_encode($evt));
}
}
@aronduby
Copy link
Author

the subdomain variable is just a room to split connections up to within socket.io. This was used as part of a service where individual things would be hosted under unique subdomains

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