Quantcast
Channel: How to concurrently send data to multiple servers using C++ socket programming? - Stack Overflow
Viewing all articles
Browse latest Browse all 3

How to concurrently send data to multiple servers using C++ socket programming?

$
0
0

I deployed one program onto several servers (suppose the server IPs and the ports providing the service are 192.168.1.101:10001, 192.168.1.102:10001, 192.168.1.103:10001, 192.168.1.104:10001). They are all listening requests using the Linux socket apis and can finish the task independently.

Now, I want to concurrently send data to all four servers, so that they can concurrently executing the tasks.

I am sending the data using one Windows 10 PC, using C++ Socket. The basic procedure of send_data is as follows:

void send_data(string& server_ip, string& server_port, vector<char>& buf) {    struct addrinfo ...;           // set the server information    SOCKET socket = socket(...);   // create the socket object    connect(socket, ...);          // connect the server    send(socket, buf, ...);        // send the buf data}

This is OK when sending sequentially data into the four servers, e.g.,

vector<char> bufdata(...);char* server_ips = {"192.168.1.101", "192.168.1.102", "192.168.1.103", "192.168.1.104"};char* port = "10001";for (int i = 0; i < 4; ++i) {    send_data(server_ips[i], port, bufdata);}

What I expect is the host client can concurrently send the data. I have tried the following method:

for (int i = 0; i < 4; ++i) {    std::thread t(send_data, server_ips[i], port, bufdata); }

But the program will exit with no luck.

Could you please help give some advice? Thanks.


Viewing all articles
Browse latest Browse all 3

Trending Articles