What is the correct way of reading from a TCP socket in C/C++?

前端 未结 8 1487
后悔当初
后悔当初 2020-11-28 04:33

Here\'s my code:

// Not all headers are relevant to the code snippet.
#include 
#include 
#include 
#in         


        
8条回答
  •  被撕碎了的回忆
    2020-11-28 04:51

    1) Others (especially dirkgently) have noted that buffer needs to be allocated some memory space. For smallish values of N (say, N <= 4096), you can also allocate it on the stack:

    #define BUFFER_SIZE 4096
    char buffer[BUFFER_SIZE]
    

    This saves you the worry of ensuring that you delete[] the buffer should an exception be thrown.

    But remember that stacks are finite in size (so are heaps, but stacks are finiter), so you don't want to put too much there.

    2) On a -1 return code, you should not simply return immediately (throwing an exception immediately is even more sketchy.) There are certain normal conditions that you need to handle, if your code is to be anything more than a short homework assignment. For example, EAGAIN may be returned in errno if no data is currently available on a non-blocking socket. Have a look at the man page for read(2).

提交回复
热议问题