Hello guys i would like to figure out what is the error in my code, my code is about socket.io and redis pub/sub it is my first time to try this, I hope you can help me guys.
This is my index.html
<!doctype html>
<html>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = new io.Socket();
socket.connect();
socket.on('connection', function (socket) {
console.log('Connected');
});
socket.on('disconnect', function (socket) {
console.log('Disconnected');
});
</script>
<center>
<h1>Test Page</h1>
</center>
</html>
This is my app.js
var redis = require('redis');
var app = require('http').createServer();
var io = require('socket.io').listen(app);
var client = redis.createClient();
var pub = redis.createClient();
var sub = redis.createClient();
app.listen(1234);
io.sockets.on('connection', function (socket){
sub.on('subscribe', function (channel){
pub.publish('Pub','Test Message 1');
pub.publish('Pub','Test Message 2');
pub.publish('Pub','Test Message 3');
});
sub.on('message', function (channel, message) {
console.log(channel + ':' + message);
sub.unsubscribe();
pub.end();
sub.end();
});
sub.incr('Channel Test');
sub.incr('Pub');
});
I hope you can help me fix this code. Thanks in advance guys.
I can see many errors in your code :
http://localhost:1234/, because it's defined in your server code.var client is not used in app.jssub is never subscribing to something. You need to subscribe to a channelsubscriber mode can not send commands to redis : only commands that modify the subscription set are validsub.incr will never publish a message : you have to call publish.pub.end() or sub.end() because the connection will be closed.message under connection event : memory leakI don't know exactly what do you want to do but here is an updated version :
index.html
<!doctype html>
<html>
<script src="http://localhost:1234/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:1234/');
socket.on('connection', function (socket) {
console.log('Connected');
});
socket.on('disconnect', function (socket) {
console.log('Disconnected');
});
</script>
<center>
<h1>Test Page</h1>
</center>
</html>
app.js
var redis = require('redis');
var app = require('http').createServer();
var io = require('socket.io').listen(app);
var pub = redis.createClient();
var sub = redis.createClient();
app.listen(1234);
sub.subscribe('Pub');//subscribe to Pub channel
sub.on('message', function (channel, message) {
console.log(channel + ':' + message);
});
io.sockets.on('connection', function (socket) {
pub.publish('Pub', 'New Connection');
pub.incr('Channel Test'); //increment 'Channel Test' but do not publish messages
pub.incr('Pub'); //increment 'Pub' but do not publish messages
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With