Search code examples
node.jswebsocketfayesocket.io

POST to controller action in node and trigger websocket connection to client


New to node and websockets, I'm trying something to create something unlike the typical game or chat app.

I need to be able to post some variables to an action, perform some lookups and then connect to the client with the found vars. I genuinely don't know if this is possible.

The major problem I'm having is that I don't have a typical js client, no browser, nada. My only clients are python websocket clients. I have these connecting to the server OK... Well, they can ping a the server - I'm trying with Socket.io, Faye and Worlize. I'd prefer to use socket.io.

For example, if I post this:

 curl -X POST 'http://localhost:8080/timeout?id=1238763876&time=27365716576&bla=stuff' 

In my app.js I have something like this (some bits missing, my socket.io example):

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/public/index.html');
});

app.post('/timeout', function (req, res) {

  //Find socket, not implemented yet

  console.log('I received a private message by ', from, ' saying ', msg);

  io.sockets.on('connection', function (socket) {
    io.sockets.emit('this', { will: 'be received by everyone'});        
  });

});

server.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

The route works but when I post, I get nothing bad and no errors - like I said, I'm new to Node from Rails. Am hoping it's something straight forward.

Is is possible to do such a thing? Is this the way to go about it or should I try something else.


Solution

  • Figured this out with the following:

    app.post('/commands/:action/:to', function (req, res) {
     target_socket = connections[req.params.to] 
     if (target_socket) {
       console.log(req.query)
       io.sockets.socket(target_socket.id).emit('name', 'stuff');
       res.send(200);
     }
     else
      res.send(404);
    });
    

    Inspiration taken this site..