R
R
Rail Khusnutdinov2017-02-22 09:23:21
JavaScript
Rail Khusnutdinov, 2017-02-22 09:23:21

How to asynchronously process received data by a socket? Event 'data' is not asynchronous?

When writing a simple event:

const EventEmitter = require('events');
let myEmitter = new EventEmitter();

myEmitter.on('aaa', (d) => {
  let ii = 1;
  console.log('функция начала выполняться');
  setImmediate(() => {
    for (let i = 1; i < 1000000000; i++) {
      ii = ii * i;
    }
    console.log(d);
  });
  console.log('функция выполнилась');
});

myEmitter.emit('aaa', 1);
myEmitter.emit('aaa', 2);
myEmitter.emit('aaa', 3);

The result is output asynchronously:
функция выполнилась
функция начала выполняться
функция выполнилась
функция начала выполняться
функция выполнилась
1
2
3

But in sockets, the 'data' event is processed synchronously, the next event does not start executing until the previous event has completed:
const net = require('net');
const fs = require('fs');
const UNIX_DOMAIN_PATH = '/tmp/sockets';

try{
  fs.unlinkSync(UNIX_DOMAIN_PATH + '/test.sock');
} catch (err) {}

const server = net.createServer();
server.on('connection', handleConnection);
server.listen(UNIX_DOMAIN_PATH + '/test.sock');

function handleConnection(conn) {

  console.log('new client connection');
  let i = 0;
  conn.on('data', (d) => {
    i++;
    console.log('i = ' + i);

    setImmediate(() => {
      let ii = 1;
      console.log('функция начала выполняться');
      console.log(d);
      for (let i = 1; i < 1000000000; i++) {
        ii = ii * i;
      }
      console.log('функция выполнилась');
    });

    console.log('end');
  });

  conn.once('close', onConnClose);
  conn.on('error', onConnError);
  function onConnClose() {
    console.log('connection closed');
  }
  function onConnError(err) {
    console.log('Connection error: %s', err.message);
  }

}

Result when sent to nc -U /tmp/sockets/test.sockdata socket:
new client connection
i = 1
end
функция начала выполняться
<Buffer 31 0a>
функция выполнилась
i = 2
end
функция начала выполняться
<Buffer 31 0a>
функция выполнилась

How to handle events asynchronously?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Doniy, 2017-02-22
@doniys_a

Maybe promises will help?
Here is an implementation example

A
Alexander Bublikov, 2017-02-22
@bublik462

in general, nodejs is an asynchronous engine.
what result do you want to get? at the exit .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question