Sign in to follow this  
cherryhouse

'dual' sending/receiving

Recommended Posts

I just want to know if something like this will create any problems. I am pretty sure I will run into problems, but I'm not really in a good state of mind for thinking right now, too loud, too much on my mind etc.
//Send loop
void send_loop()
{
    
    char buf[256],
         buf2[256];

    send(fd, buf, sizeof(buf), 0);
    send(fd, buf2, sizeof(buf2), 0);
}

//Receive loop
void recv_loop()
{
    int bytes,
        cmd; 
    
    char buf[256];

    if((bytes = recv(i, buf, sizeof(buf), 0)) <= 0)
        {
            if(bytes == 0)
            {
                std::cout<<"Client "<<inet_ntoa(Raddr.sin_addr)<<" closed on socket "<<i<<std::endl;
            }
            closesocket(i);
            FD_CLR(i, &master);
        }

    cmd = atoi (buf);    //Convert the buf string to integer for later use with switch-statement for selecting which command the user chose

    if((bytes = recv(i, buf, sizeof(buf), 0)) <= 0)//Recv the string to output to the console incase cmd==1, which is the print to console command
        {
            if(bytes == 0)
            {
                std::cout<<"Client "<<inet_ntoa(Raddr.sin_addr)<<" closed on socket "<<i<<std::endl;
            }
            closesocket(i);
            FD_CLR(i, &master);
        }

    std::cout << buf << std::endl;
I just need to know if this would work. The user would enter to the console, for a say function: "1 hello", which would select the say command and print hello to the screen.

Share this post


Link to post
Share on other sites
That almost certainly won't work. One call to send() could be picked up by 2 calls to recv(), and 2 calls to send() could be picked up by 1 recv(). In your case, TCP will almost certainly merge the two send()s into one packet, and they'll be picked up by one call to recv().
You'd need to use UDP (which is unreliable and doesn't guarantee the order the packets arrive in), but is faster, or use some kind of tokenizing in the TCP stream.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this