Skip to content

Instantly share code, notes, and snippets.

@pedrommone
Created December 23, 2014 11:42
Show Gist options
  • Save pedrommone/29d4d14f496a0fa577b9 to your computer and use it in GitHub Desktop.
Save pedrommone/29d4d14f496a0fa577b9 to your computer and use it in GitHub Desktop.
Socket.io implementantion with Redis, Laravel and Node.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Laravel PHP Framework</title>
<style>
</style>
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
<script type="text/javascript">// <![CDATA[
var socket = io.connect('http://107.170.63.247:3000', {
query: 'user_id={{ Session::getId() }}'
});
socket.on('connect', function(data) {
socket.emit('subscribe', { channel: 'notifications' });
});
socket.on('notifications', function (data) {
console.log(data);
});
// ]]></script>
</head>
<body></body>
</html>
<?php
Route::get('/', function()
{
return View::make('hello');
});
Route::get('/t', function() {
$time = time();
$redis = Redis::connection();
$redis->publish('actions', json_encode([
'client_id' => Session::getId(),
'data' => $time
]));
return "Pushed " . $time . " into " . Session::getId();
});
var express = require('express'),
http = require('http'),
sys = require('sys'),
redis = require('redis')
io = require('socket.io');
var app = express(),
server = http.createServer(app),
clients = {};
server.listen(3000, '107.170.63.247');
io.listen(server).on('connection', function(client) {
var client_id = client.handshake.query.user_id;
if (typeof clients[client_id] == 'undefined')
clients[client_id] = [];
clients[client_id].push(client);
console.log('Connected: ' + client_id);
});
var redisClient = redis.createClient()
redisClient.subscribe('actions');
redisClient.on("message", function(channel, message) {
var response = JSON.parse(message);
try {
clients[response.client_id].forEach(function(client) {
client.emit('notifications', response.data);
console.log('Pushed ' + response.data + ' to ' + response.client_id);
});
}
catch ( error ) {}
});
@cuautorres
Copy link

Sorry but on line 20 of your code clients[client_id].push(client); each you see that a user enters the URL or refresh the page we add or push a new element to the array, which makes long time a huge arrangement that has to read everything in your foreach line 34 check your code.

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