Sunday 12 March 2017

nodejs - how to write a client that connects to a nodeJS Server and receives broadcast message

I have the following nodeJS Server that seems to work fine. I would like to write a client that receives message from the server and invokes some JS based on the message.

The steps involved are:

  1. User accesses the url http://server.xyz.com:8080/pa
  2. nodeJS Server receives that call and broadcasts to the connected clients that pa is the api call received.
  3. nodeJS Clients that are connected to the server invoke some JS related to the pa action.

My questions are:

1. How do I make sure the server broadcasts that message like Step 2?
2. How do I write a client that performs Step 3 above.

For the client, I am seeing a lot of references to socket.io, but I am not sure what's the best framework in this case.

server.js

var http = require('http');

http.createServer(function(request, response) {
  request.on('error', function(err) {
    console.error(err);
    response.statusCode = 400;
    response.end();
  });
  response.on('error', function(err) {
    console.error(err);
  });

  response.writeHead(200, {'Content-Type': 'application/json'});
  var body=[];
  if (request.method === 'GET' && request.url === '/pa') {
    response.end(JSON.stringify({"action": "pa"}));
  }
  else if (request.method === 'GET' && request.url === '/pi') {
    response.end(JSON.stringify({"action": "pi"}));
  }
   else {
    response.statusCode = 404;
    response.end();
  }
}).listen(8080);



via Jake

No comments:

Post a Comment