Skip to content Skip to sidebar Skip to footer

Using Socket Io And Aiohttp For Data Transfer Between Node Js And Python

My overall goal is to generate a stream of random numbers in a JavaScript file (which is run using node) and send them to a python script in asynchronous time intervals. Once the n

Solution 1:

I believe, in JS part, you should call sendMsg() somewhere in order to emit a message.

Updated

const io = require('socket.io-client');

const socket = io('http://localhost:8080');

socket.on('message', data => {
  console.log('Got from server: ');
  console.log(data);
});

functiongenerateNumber() {
  const n = Math.floor(Math.random() * 50);
  return { number: n };
}

functionsendMsg() {
  const json = generateNumber();
  console.log('Sending to server:');
  console.log(json);

  socket.emit('message', json);
}

functionloop() {
  const rand = Math.round(Math.random() * (3000 - 500)) + 500;
  console.log(`Setting timeout ${rand}ms`);
  setTimeout(() => {
    sendMsg();
    loop();
  }, rand);
}

socket.on('connect', () => {
  console.log('Connected to server');
  loop();
});

I was using node on both sides. The server side just sends back every received message. The logs look like this:

Connected to server
Setting timeout 1685ms
Sending to server:
{ number: 21 }
Setting timeout 1428ms
Got from server: 
{ number: 21 }
Sending to server:
{ number: 40 }
Setting timeout 2955ms
Got from server: 
{ number: 40 }

Post a Comment for "Using Socket Io And Aiohttp For Data Transfer Between Node Js And Python"