简体   繁体   中英

Streaming search queries with Node.js and Socket.io (streaming to a given socket!)

I am writing a simple app in Node that will collect search queries on client side, send it to Node server and from server to admin page where I can track 'em. However I want to keep in mind security so I want to send search queries from Node ONLY to admin page. This is what I have so far:

Node Server:

var socket = io.listen(app);
socket.on('connection', function(client){
  client.on('message', function(data){
    socket.broadcast(data);
  });
});

Client:

$.getScript('http://127.0.0.1:8000/socket.io/socket.io.js', function() {
    var socket = new io.Socket('127.0.0.1', {'port': 8000});
    socket.connect();
    socket.send(search_query);
    });
});

Admin:

$(document).ready(function(){
  socket = new io.Socket('172.20.14.114', {port: 3000});
  socket.connect();
  socket.on('message', function(data){
    console.log(data);
  });
});

The code above works perfectly but I want to pipe 'search_query' ONLY to the admin page (due to security reasons). Now my Node server broadcasts data everywhere. How do I modify my script? Thanks in advance.

I'd have the admin send a message to the server (something more secure than 'AdminLogin') to register as admin, then you can simply send to that one client.

Server:

var socket = io.listen(app), admin;
socket.on('connection', function(client){
  client.on('message', function(data){
    if( data === 'AdminLogin' ) {
      admin = client;
    }
    if( admin ) {
     admin.send(data);
    }
  });
});

Admin:

$(document).ready(function(){
  socket = new io.Socket('172.20.14.114', {port: 3000});
  socket.connect();
  socket.send('AdminLogin');
  socket.on('message', function(data){
    console.log(data);
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM