简体   繁体   中英

Handling packets received from multiple clients to multiple threads in c

when multiple clients send packets to server how can i write code to receive them on their corresponding child threads instead of receiving them on main process

i am writing c program for udp client and server using threads so if i have 4 clients connected 4 threads will be created and each thread will send some data. after receiving the data the clients will send acks but the problem is those acks should be received by the corresponding threads but

i have receivefrom function in main process to listen for new clients and i also have receivefrom function on threads to get ack packets but these ack coming from client are going to main process instead of coming to threads please help me thanks in advance

my code server code

//created udp socket

// binded

while(1)
{
    // to receive new connections 
    n=recvfrom(sock,buffer,512,0,(struct sockaddr*)&from,&length);  

    // if some client sent request i will assign new thread to serve it
    pthread_create(&thread_id[str_cnt], NULL, serve,(void*)(&cli[str_cnt])); 
}

function serve(args)
{

    while(1)
    {   
        // sendind data to that client
        sendto(sockfd, buf, BUFSIZE, 0, (struct sockaddr *) &clientaddr,clientlen);

        //now wating for ack from the client
        sendto(sockfd, buf, BUFSIZE, 0, (struct sockaddr *) &clientaddr,clientlen);
    }
}

}

You can't have multiple threads reading from the same socket at the same time.

What you should do instead is either:

  1. have a dedicated thread that receives all inbound packets, looks at the source IP/Port, and routes the data to the appropriate processing thread as needed.

  2. give each processing thread its own socket that is bind() 'ed to the same local IP/Port and connect() 'ed to the particular source IP/Port it is interested in, then each thread can call recvfrom() independently and it will only return packets that match the source that the thread is expecting.

I took this from Remy Lebeau on this question .

UDP doesn't have a notion of separate connections unless you use different ports and handle them yourself, that's why they created TCP (and also for more reliable, in-order communication.) You're already emulating reliable communication by using ACKs, so the only overhead is in-order communication (and checksums, if you don't like them either) so you might be better off using TCP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM