Sending and receiving strings over TCP socket separately

后端 未结 4 1335
难免孤独
难免孤独 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:30

    TCP is stream-oriented, not datagram-oriented. If it was the latter, your stuff would work great. You have the following options:

    • use SCTP
    • use UDP if you can afford losing reliability
    • separate the strings in a way you can work with, either by prepending a length tag or so or by adding a NUL byte for terminating each string.

    For the latter, you would just do send(*socket, buffer, strlen(buffer)+1, 0); for including the NUL which is here nevertheless, and the sender would repeatedly recv() and find a string terminator until it has found 2 strings.

    Note that you should take care with strcpy(): only use it if you are absolutely sure that the string you are writing to is ok.

    Your receiver does

    bytes = recv(*socket, buffer, sizeof(buffer), 0);
    buffer[bytes] = '\0';
    

    That is bad because, if the buffer is full, so bytes == sizeof(buffer) (which could happen in more complex situations), buffer[bytes] = '\0' writes beyond the buffer. SO use

    bytes = recv(*socket, buffer, sizeof(buffer) - 1, 0);
    

    and you can happily do

    buffer[bytes] = '\0';
    

    .

提交回复
热议问题