Note that there are some explanatory texts on larger screens.

plurals
  1. POSending and receiving strings over TCP socket separately
    primarykey
    data
    text
    <p>I have a TCP server and client, with an established socket. Let's say I have the following case:</p> <p>SERVER:</p> <pre><code>char *fn = "John"; char *ln = "Doe"; char buffer[512]; strcpy(buffer, fn); send(*socket, buffer, strlen(buffer), 0); strcpy(buffer, ln); send(*socket, buffer, strlen(buffer), 0); </code></pre> <p>CLIENT:</p> <pre><code>char *fn; char *ln; char buffer[512]; bytes = recv(*socket, buffer, sizeof(buffer), 0); buffer[bytes] = '\0'; strcpy(fn, buffer); bytes = recv(*socket, buffer, sizeof(buffer), 0); buffer[bytes] = '\0'; strcpy(ln, buffer); printf("%s", fn); printf("%s", ln); </code></pre> <p>Expected result: I want to receive each string separately (as I am saving them in different variables), instead the first recv() gets both the fn "John" and ln "Doe" concatenated "JohnDoe", and the program gets stuck on the second recv()... since I've already done the sending.</p> <p>I tried the following: - Adding \0 to the fn and ln strings like so: </p> <pre><code>char *fn = "John\0"; char *ln = "Doe\0"; </code></pre> <p>But the problem persisted.</p> <p>Is there some sort of condition I can impose so each string is received separately?</p> <p>EDIT TO ADD MORE QUESTIONS:</p> <p>1) Why does it in certain instances actually send them separately, and others sends them jointly?</p> <p>2) Should I send() and recv() alternatively maybe? In some other parts of my code, it seems it is self regulating and only receiving the right strings at the right time without me having to check. Does this do the trick?</p> <p>3) About sending a header with the length of the string I am about to send, how do I parse the incoming string to know where to split? Any examples would be great. </p> <p>4) I will definitely check if I'm getting something bigger than my buffer, thanks for pointing to it.</p> <p>Edit 2:</p> <p>5) Since I'm always putting things in a buffer char array of size 512. Shouldn't every send operation take the full size of the buffer even if I am sending a 1 letter string? That's what confusing. I have "John" but I'm putting it in an array of size 512 and sending it, shouldn't that fill up the send buffer, and so the recv() function empties the network buffer by also pulling the whole array of size 512?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload