简体   繁体   中英

Write n bytes and read n bytes: sending number of bytes to read using uint16_t

I've been using these read and write functions (provided by @alk).
The problem is that I don't know how to correctly send the uint16_t data_size; .
Here is my actual code to send a general example buffer:

uint16_t data_size;
int retry_on_interrupt = 0;
char buffer[] = "Hello world!";
data_size = (uint16_t) sizeof(buffer);    

/* sending data_size */
writen(socket, data_size, 2, retry_on_interrupt);

/* sending buffer */
writen(socket, buffer, sizeof(buffer);  

And here is my actual code to receive a general example buffer:

/* receiving data_size */
readn(socket, &data_size, 2);

/* receiving buffer */
readn(socket, buffer, data_size);

But this is not working, I think because writen requires a const char * , instead I'm using a uint16_t ...
How should these calls be? Thanks.

Replace

writen(socket, data_size, 2, retry_on_interrupt);

by

if (-1 == writen(socket, &data_size, sizeof data_size, 1))
{
   perror("writen() failed writing size");
   exit(EXIT_FAILURE);
}

and replace this line

writen(socket, buffer, sizeof(buffer);  

by

if (-1 == writen(socket, buffer, data_size, 1))
{
   perror("writen() failed writing pay-load");
   exit(EXIT_FAILURE);
}

You definitely want to add error-checking to the reading functions as well!


Also you want to take care of a possible endianness (byte-order) issue, when sending/receiving between to different hardware-platforms.

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