Created
June 10, 2016 15:01
-
-
Save jimitit/8560108ad8cf84c562e874477f60eb6e to your computer and use it in GitHub Desktop.
Socket.io implementantion with Redis, Laravel and Node.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ) {} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment