简体   繁体   中英

When does recv() return?

I have made a server and a client using sockets. My server is written in c and runs on my raspberry pi and my client is written in Swift and is running on my Mac/iPhone.

What i don't get is when my servers recv() function execute what i have sent from my client? If i send like 0-10 bytes it doesn't return from recv() function before i close the connection. But if I send 100+ bytes it executes immediately.

I would like my server to return from recv() every time i write a message from my client.

Here is my servers recv() function:

//Receive a message from client
while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
{
    printf("%s", client_message);
}

Here is my Clients write method:

func SendMsg(msg:String) -> Int{
    return outputStream!.write(msg, maxLength: countElements(msg))
}

Everything works fine beside I'm not in control of when my server executes my messages.

Output to stdout is by default line buffered, so when using printf , make sure there is a newline character ( '\\n' ) at the end. If the message itself doesn't already contain a newline, then :

printf("%s\n", client_message);

As a side note : also make sure that client_message is properly null terminated before passing it to printf , or you might run into undefined behavior (ref. @JoachimPileborg's comment). If you can't ensure null termination, this would do the trick too :

printf("%.*s\n", read_size, client_message);

The server doesn't get the message because the client hasn't sent it.

You need to fflush the outputStream on the client side!

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