简体   繁体   中英

Windows C socket, read N bytes from the socket stream

How do i read exactly N bytes from the socket stream in C on windows 10, the only function i was able to find is recv() that reads everything.

As the official documentation says , you have to pass to the recv() function 4 parameters:

  • s - The socket descriptor
  • buf - The memory buffer which will hold the read data
  • len - The length of the memory buffer
  • flags - "A flag or a set of flags that influence the behavior of this function"

In particular, when the last parameter is set to the defined value MSG_WAITALL , the recv() function will complete only when one of these events occurs:

  • The buffer supplied by the caller is completely full.
  • The connection has been closed.
  • The request has been canceled or an error occurred.

In other words, if you want to read exactly 10 bytes, you should create a 10 bytes buffer and ask the recv() function to return only once the buffer is full!

char data[10];
recv(streamSocket, data, 10, MSG_WAITALL);

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM