Kobi Guetta
Kobi Guetta

Reputation: 105

client messages don't arrive to server in tcp winsock

I have server client application. When I'm sending messages in a row(without scanf in the code below), it's seems the server doesn't get them(doesn't print). if I wait a little bit(with the scanf in the code below) and then send the next message the server works fine and prints all messages.

what's the problem? how can I fix it, cause I want to do more with the message(not just to print it) that arrived to the server.

in my client code(where server prints nothing)

char message[(100)] = {0};
int x = rand();
while(i < 3)
    {
        printf(" I send %d\n", x);fflush(NULL);
        sprintf(message, "%d",x);
        if( send(mainSockfd, message,strlen(message),0) == -1)
        {
            printf("ERRRRRORRRR\n");fflush(NULL);
        }
        i++;
        x = rand() % 100;
    }

in my client code(when server prints the messages)

char message[(100)] = {0};
int x = rand();
while(i < 3)
{
    printf(" I send %d\n", x);fflush(NULL);
    sprintf(message, "%d",x);
    if( send(mainSockfd, message,strlen(message),0) == -1)
    {
        printf("ERRRRRORRRR\n");fflush(NULL);
    }
    i++;
    x = rand() % 100;
    scanf("%d",&x); // this is the only change
}

in my server code

char command[(100+1)] = {0};
while(1)
    {
        readLength = recv(sockfd, command, 100+1,0);
        if(readLength > 0)
        {
            printf("arrived = %s,\n",command);fflush(NULL);
            ZeroMemory(command, sizeof(command));
        }
        else if( readLength == 0)
                {
                    break;
                }
        else if ( readLength < 0 ){
            if(GetLastError() == 10035)
            {
                continue;
            }
            if(GetLastError() == 10057 || GetLastError() == 10054)
            {
                break;
            }
            continue;
        }
    }

Upvotes: 0

Views: 347

Answers (1)

alk
alk

Reputation: 70971

As you seem to be transferring 0-terminated "strings" without the 0 termination, you should read one char less then the read buffer provides to always have the read buffer being 0-terminated, as if you try to printf a non 0-terminated "string" you provoke undefined behaviour.

So change this

readLength = recv(sockfd, command, 100+1,0);

to become this

readLength = recv(sockfd, command, 100,0);

Upvotes: 1

Related Questions