The next item is the socket.js file.
The original suggestion was to use this code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('test-channel', function(err, count) {
});
redis.on('message', function(channel, message) {
console.log('Message Recieved: ' + message);
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.data);
});
http.listen(3000, function(){
console.log('Listening on Port 3000');
});
However, (perhaps this was written before Taylor got to rewrite all his documentation for 5.1) there seems to be a much better and more flexible script we can use directly out of the Laravel Docs.
If we take a look at the broadcasting docs, we can see that the following code allows more flexibility:
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var Redis = require('ioredis');
var redis = new Redis();
app.listen(6001, function() {
console.log('Server is running!');
});
function handler(req, res) {
res.writeHead(200);
res.end('');
}
io.on('connection', function(socket) {
//
});
redis.psubscribe('*', function(err, count) {
//
});
redis.on('pmessage', function(subscribed, channel, message) {
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.data);
});
The main benefit is that we don't have to hard code any channel name into our socket.js file. With Taylor's new code the socket.io script can listen/subscribe on ANY channel. Less hard coding = more goodness!
I have been using Taylors new suggested code for weeks, and it's working perfectly.
As a side note for those who need to create a https node/socket.io server (the above code is only for a http server and you will have issues if you try to create a https node.js server and allow a non https connection to it) the following code works well.
var fs = require('fs');
// This line is from the Node.js HTTPS documentation.
var options = {
key: fs.readFileSync('/etc/nginx/ssl/<makeyourownpath>/server.key'),
cert: fs.readFileSync('/etc/nginx/ssl/<makeyourownpath>/server.crt')
};
var app = require('https').createServer(options, handler);
var io = require('socket.io')(app);
var Redis = require('ioredis');
var redis = new Redis();
app.listen(6001, function() {
console.log('Server is running on port 6001!');
});
function handler(req, res) {
res.writeHead(200);
res.end('');
}
io.on('connection', function(socket) {
//
});
redis.psubscribe('*', function(err, count) {
//
});
redis.on('pmessage', function(subscribed, channel, message) {
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.data);
});