How can I block a non-blocking IO?

When I need buffered IO when blocking a file descriptor, I use stdio. But if I turn the file descriptor into non-blocking mode according to the manual stdio buffering, this is not suitable. After some research, I see that BIO can be used to buffer non-blocking IOs.

But there may be other alternatives?

I need this to avoid using threads in a multi-connection environment.

+3
source share
5 answers

I think what you are saying is a Reactor Pattern . This is a fairly standard way of handling multiple network connections without streams and is very common in multi-player game servers. Another implementation (in python) is a twisted matrix .

The main algorithm:

  • have a buffer for each socket
  • check which sockets are ready to read (select (), poll () or just iteration).
  • for each socket:
    • call recv () and copy the contents to the socket buffer until recv returns 0 or there is an error with EWOULDBLOCK
    • calling an application-level data handler for a socket with buffer contents
    • clear socket buffer
+15
source

I see that the question has been edited now and is at least more understandable than before.

, ?

  • I/O, , .
  • , , , - .

.

, ? :

int     fd;
char    buf[1024];
ssize_t got;

fd = setup_non_blocking_io(...);
got = read(fd, buf, sizeof buf);

, 3 ? / - , , - 3 .

, - , - , , " - , , ", , .

+3

, , , node ( ).

, (), ( , , ). () , ..

Java ( ) io (NIO) (ByteBuffer ..), .

C, . , (, ) .

Android, ( ) .

+1

, , recv() 0 .

, , ( ) ( ).

, (, ) .

Threading , , .

0

Ryan Dahl evcom, , .

I use it in my work and it works great. Keep in mind, however, that it does not (yet, but in the near future) have asynchronous DNS resolution. Ryan offers udns by Michael Tokarev . I am trying to accept udns instead of getaddrinfo () blocking.

0
source

Source: https://habr.com/ru/post/1704640/


All Articles