Using Socket IO and aiohttp for data transfer between node JS and Python

前端 未结 1 1560
花落未央
花落未央 2021-01-27 08:21

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 th

相关标签:
1条回答
  • 2021-01-27 08:47

    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);
    });
    
    function generateNumber() {
      const n = Math.floor(Math.random() * 50);
      return { number: n };
    }
    
    function sendMsg() {
      const json = generateNumber();
      console.log('Sending to server:');
      console.log(json);
    
      socket.emit('message', json);
    }
    
    function loop() {
      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 }
    
    0 讨论(0)
提交回复
热议问题