🟢 Node - WebSockets
Updated at 2013-07-04 09:05
WebSockets allow duplexed connection between client and server. Module socket.io gives abstract WebSockets with fallbacks.
Basic connection:
// SERVER
var express = require('express');
var app = express.createServer();
var socket = require('socket.io');
var io = socket.listen(app);
io.sockets.on('connection', function(client) {
console.log('Client connected');
client.on('answer', function(question, answer) {
client.broadcast.emit('answer', question, answer);
});
// When client sends event named question.
client.on('question', function(question) {
// See if this client has already asked a question.
client.get('question_asked', function(err, asked) {
// If has not asked, send question to all other clients
if ( ! asked ) {
client.broadcast.emit('question', question);
client.set('question_asked', true);
}
});
});
});
<!-- CLIENT -->
<script src="/socket.io/socket.io.js"></script>
<script>
var server = io.connect('http://localhost:8080');
server.on('question', function(question) {
insertQuestion(question);
});
server.on('answer', function(question, answer) {
answerQuestion(question, answer);
});
</script>
Using redis to as persisting data storage with socket.io
npm install redis
var redis = require('redis');
var client = redis.createClient();
client.set('message1', 'hello!');
client.set('message2', 'yo!');
// Non-blocking!
client.get('message1', function(error, reply) {
console.log(reply);
});
More complex:
var express = require('express');
var app = express.createServer();
var socket = require('socket.io');
var io = socket.listen(app);
var redis = require('redis');
var redisClient = redis.createClient();
io.sockets.on('connection', function(client) {
// Send saved questions to new clients.
redisClient.lrange('questions', 0, -1, function(err, questions) {
questions.forEach(function(question) {
client.emit('question', question);
});
})
// On 'answer', sent same event to all other clients.
client.on('answer', function(question, answer) {
client.broadcast.emit('answer', question, answer);
});
//
client.on('question', function(question) {
client.get('question_asked', function(asked) {
if ( ! asked ) {
client.set('question_asked', true);
client.broadcast.emit('question', question);
redisClient.lpush(
'questions',
question,
function(error, reply) {
redisClient.ltrim('questions', 0, 19)
}
);
}
});
});
});