Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
simple chat client using redis pub/sub
var q= function(s){ return document.getElementById(s) }
function send(){
var input = q('text');
socket.send(input.value);
input.value = '';
}
var socket = new io.Socket(null, {
port: 8001,
rememberTransport: false
});
socket.on('message', function(message){
var el = document.createElement('p');
el.innerHTML = message;
q('chat').appendChild(el);
});
socket.connect();
!!! 5
html(lang="en")
head
title chat
meta(charset="utf-8")
link(rel="stylesheet", href="/master.css")
script(src="http://cdn.socket.io/stable/socket.io.js")
script(src="/application.js")
body
h1 Sample chat client
div#chat
form#form(onsubmit="send();return false")
input#text(type="text", autocomplete="off")
#chat p {
padding: 8px;
margin: 0;
}
#chat p:nth-child(odd) {
background: #F6F6F6;
}
form {
background: #444;
padding: 5px 10px;
}
form input[type=text] {
width: 98%;
padding: 5px;
background: #fff;
}
{
"name": "redispubsub",
"version": "0.0.2",
"dependencies": {
"connect": "1.3.0",
"express": "2.2.1",
"jade": "0.10.4",
"socket.io": "0.6.17",
"redis":"0.5.11"
}
}
var express = require("express")
var socketio = require("socket.io")
var redis = require("redis")
// redis clients
var store = redis.createClient()
var pub = redis.createClient()
var sub = redis.createClient()
var app = express.createServer(express.static(__dirname + '/public'))
app.set('view engine', 'jade')
app.get("/", function(req, rsp){
rsp.render('index', { layout: false })
})
app.listen(8001)
var socket = socketio.listen(app)
sub.subscribe("chat")
socket.on("connection", function(client){
client.send("welcome!")
client.on("message", function(text){
store.incr("messageNextId", function(e, id){
store.hmset("messages:" + id, { uid: client.sessionId, text: text }, function(e, r){
pub.publish("chat", "messages:" + id)
})
})
})
client.on("disconnect", function(){
client.broadcast(client.sessionId + " disconnected")
})
sub.on("message", function(pattern, key){
store.hgetall(key, function(e, obj){
client.send(obj.uid + ": " + obj.text)
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.