user606521
user606521

Reputation: 15424

socket.io along with restify REST api

I have implemented REST API using restify.js. It is deployed on heroku. Now I want to add real-time communication between server and users (mobile apps). My idea is to emit events to clients to 'tell' them when any data are available for them (and they can call normal REST api to fetch this data). I am using redis PUB/SUB in my app to broadcast events.

So my very simpliefied code looks like this:

var redisClient = require('./redis-client');
var app = restify.createServer();

app.get('/give-me-data',function(req,res,next){
    res.json('{ data: 'abcdef' });
});

redisClient.on('message',function(channel,message){
    if(message=='data-available') {
        // now I want to emit event to mobile clients through socket.io
    }
});

redisClient.subscribe('data-available-channel');

app.listen(process.env.PORT);

How I can add socket.io to such app to let clients (mobile apps) connect to it and listen for events?

Upvotes: 1

Views: 2897

Answers (1)

Krasimir
Krasimir

Reputation: 13529

You may use socket.io. Here is an article showing simple application (real time game). It's pretty simple actually. I'll suggest to send the data directly via the socket. You will save one request. I mean your client will receive the message via the token and after that will make a request to the API. So, you may save this.

Server:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

client:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

Upvotes: 2

Related Questions