Tuesday 14 March 2017

How to broadcast a specific parameter

I have the following nodeJS code. When a user makes an API call, http://server.xyz.com:8080/pa I would like the nodeJS server to broadcast pa to all connected clients. Similarly, if the user makes an API Call http://server.xyz.com:8080/pi, I would like the nodeJS server to broadcast pi to all connected clients.

The client then should be able to get the op parameter, and based on if it gets pa or pi, it should alert something.

How do I do that? My server code doesn't seem to broadcast when it receives the API call. The client connects just fine.

server.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var operation = "";
http.listen(8080, function(){
  console.log('listening on *:8080');
});
app.get('/pa', function(req, res){
    operation = "pa";
    res.end(operation);
});

app.get('/pi', function(req, res){
        operation = "pi";
        res.end(operation);
});

io.sockets.on('connection', function (socket) {
    console.log("Client Connected");
    socket.broadcast.emit('op', operation);
});

client.js

$(document).ready(function()
{
    var socket = '';
    socket = io.connect("http://server.xyz.com:8080");
    socket.on('connection', function(socket) {
               socket.on("op", function(d) {
               console.log("Server sent something ");
              });   
    });
});



via Jake

No comments:

Post a Comment