Sending and receiving strings over TCP socket separately

后端 未结 4 1346
难免孤独
难免孤独 2021-02-10 19:17

I have a TCP server and client, with an established socket. Let\'s say I have the following case:

SERVER:

char *fn = \"John\";
char *ln = \"Doe\";

char          


        
4条回答
  •  走了就别回头了
    2021-02-10 19:24

    The right thing to do is to enclose the sent data with a header. So you would pass the size of the message, including the size of the message, then on the other side you can figure out how long the message should be.

    John is 4 chars, so you have the length, something like "0004John" then you would know when to stop reading. You may also want to add a command to the header, that is very common. So for instance, first name might be 1, and second name 2;

    "01004JOHN" for instance would be set in the buffer and sent.

    To do this, you add items to the buffer, then increment the insertion point in the buffer by the sizeof the values you added. You can use this to add many parts to the buffer. *Just be sure you dont overrun the size of the buffer.

    Remember these examples im giving are not correct, because you dont pass the string representation of the number, just the number, so it would be a long int 1, long int 4 and then chars, or unicode, either way, 4 characters.

提交回复
热议问题