Search code examples
node.jswebsocketsocket.ionode.js-client

WS websocket send() as a function


I'm having some issues with this. I'm connecting with socket.io (works) to another server, I want to send by WS to a client (processing). The main problem is that it just sends once, I want to send all the time that the socket.io gets an input.

Actual code:

var io = require("socket.io-client");
var socket = io.connect('http://socket.io.server:8000');
var WebSocketServer = require('ws').Server
 , wss = new WebSocketServer({port: 8080});

var temp = 0;

socket.on('connect', function () {
    console.log("socket connected") ;
});

socket.on('udp message', function(msg) { 
    temp = msg/100;
    console.log(temp) ;
    wss.on('connection', function(ws) {
          ws.send(temp.toString());
    });
});

What I Wanted:

socket.on('udp message', function(msg) { 
    temp = msg/100;
    console.log(temp) ;
    ws.send(temp.toString());

});


 wss.on('connection', function(ws) {
    console.log("Connected to client")
});

This way I could have a realtime data in my WS client.


Solution

  • If you have to deal with only one WebSocket client, you can do this:

    var ws = null;
    socket.on('udp message', function(msg) { 
      var temp = msg/100;
      console.log(temp);
      // make sure we have a connection
      if (ws !== null) {
        ws.send(temp.toString());
      }
    });
    
    wss.on('connection', function(_ws) {
      console.log("Connected to client");
      ws = _ws;
    });
    

    If you have multiple WebSocket clients, you need to store their _ws in an array and with each incoming udp message event, send it to each WebSocket client stored in that array.