简体   繁体   English

写入 n 个字节并读取 n 个字节:使用 uint16_t 发送要读取的字节数

[英]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).我一直在使用这些读取写入功能(通过@alk提供)。
The problem is that I don't know how to correctly send the uint16_t data_size;问题是我不知道如何正确发送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 ...但这不起作用,我认为是因为writen需要一个const char * ,而我使用的是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.在不同的硬件平台之间发送/接收时,您还想处理可能的字节序(字节顺序)问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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