Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle asynchronous socket receiving in C++?

I'm currently using a thread to handle Connect and Send calls asynchronously. This is all working fine, but now I want to make receiving asynchronous too. How should I receive data without pausing the whole queue while waiting for data? The only solution I can think of right now is a second thread.

like image 270
Overv Avatar asked Jun 10 '10 18:06

Overv


People also ask

What is asynchronous socket connection?

In an asynchronous socket, you CAN do other stuff while waiting for the client to send data to you, so now you CAN have multiple clients connecting to you. Synchronous uses a function like receive() which blocks until it gets a message. Asynchronous has beginReceive() endReceive() or similar functions.

What is the difference between synchronous sockets and asynchronous sockets?

The send, receive, and reply operations may be synchronous or asynchronous. A synchronous operation blocks a process till the operation completes. An asynchronous operation is non-blocking and only initiates the operation.

Is socket accept a blocking call?

The default mode of socket calls is blocking. A blocking call does not return to your program until the event you requested has been completed.

How do sockets work in C?

Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server.


2 Answers

Look into non-blocking sockets and polling APIs like select(2)/poll(2)/epoll(4)/kqueue(2).

Specifically in C++, look into boost::asio.

like image 173
Nikolai Fetissov Avatar answered Sep 28 '22 13:09

Nikolai Fetissov


Depending on what you're doing, non-blocking I/O with select may be the answer.

Take a look at this tutorial.

like image 27
Robert S. Barnes Avatar answered Sep 28 '22 14:09

Robert S. Barnes