joncodo
joncodo

Reputation: 2328

How to set up node socket connection and access with REST

I want to have a route on my sailsjs node server that is a socket connection. I want to then send a rest request to that route from outside the app and have the socket hear the event and update the UI of my app.

So far all I have seen on the web is to have a websocket server by itself. Is there no way to integrate it into an existing server?

I'm a bit lost here. Can anyone point me to a tutorial that is doing this?

Question: How do I send a rest request to my server from outside the app and have the server update the UI of my app?

If you need more clarity here, please let me know.

Upvotes: 1

Views: 77

Answers (2)

Ran Bar-Zik
Ran Bar-Zik

Reputation: 1237

Use socket.io, it can be added to every Node.js server. For example:

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs');

app.listen( 80 );

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(data);
  });
}

io.set('log level', 1);

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

You can use any socket event here.

Upvotes: 0

birkett
birkett

Reputation: 10101

You Have to use WebSockets I think. The UI does not know anything about the server unless it is notified. The only other way to have it running without WebSockets is to have a long polling AJAX request, but that solution would work for a limited use cases.

Adding a Socket.io server to a node server is pretty trivial, I would give it a try.

Upvotes: 1

Related Questions