user2986042
user2986042

Reputation: 1268

How socket send data?

I got a snippet from internet for send data through a socket .

Here is the code .

u32_t nLength = 0;
u32_t nOffset = 0;

do {
    nLength = nFullLength - nOffset;
    status = Socket->Send(((u8_t*) buff) + nOffset, &nLength);
    if (status != ERROR_SUCCESS) {
        break;
    }
    nOffset += nLength;
} while (nOffset < nFullLength);

My doubts are :

When send(sock_fd, buf+bytes, buflen-bytes, flags); function running , it will send the entire data ?

Let's assume i have a buff with 45 byte length . So it will send like

send(buf+0, 45-0) = send(buf+0, 45);

So it will send complete data with length 45 ? what is the use of length here ? initially it will 45 . Isn't ?

Upvotes: 0

Views: 145

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595320

TCP is a streaming transport. There is no guarantee that a given send() operation will accept all of the bytes given to it at one time. It depends on the available kernel buffer space, the I/O mode of the socket (blocking vs non-blocking), etc. send() returns the number of bytes it actually accepted and put into the kernel buffer for subsequent transmission.

In the code example shown, it appears that Socket->Send() expects nLength to be initially set to the total number of bytes to sent, and it will then update nLength with the number of bytes actually sent. The code is adjusting its nOffset variable accordingly, looping just in case send() returns fewer bytes than requested, so it can call send() as many times as it takes to send the full number of bytes.

So, for example, lets assume the kernel accepts up to 20 bytes at a time. The loop would call send() 3 times:

send(buf+0, 45-0)   // returns 20
send(buf+20, 45-20) // returns 20
send(buf+40, 45-40) // returns 5
// done

This is typical coding practice for TCP programming, given the streaming nature of TCP.

Upvotes: 1

unwind
unwind

Reputation: 399703

Well, no. There's no guarantee that it will send all the data you ask it to send, that's why the code looks the way it does.

The manual page for send() states this pretty clearly:

Return Value

On success, these calls return the number of characters sent. On error, -1 is returned, and errno is set appropriately.

The same is true for e.g. a regular write() to a local file, by the way. It might never happen, but the way the interface is designed you're supposed to handle partial sends (and writes) if they do happen.

Upvotes: 1

Related Questions