写入 n 个字节并读取 n 个字节:使用 uint16_t 发送要读取的字节数
Write n bytes and read n bytes: sending number of bytes to read using uint16_t
我一直在使用这些 read and write 函数(由@alk 提供)。
问题是我不知道如何正确发送 uint16_t data_size;
.
这是我发送通用示例缓冲区的实际代码:
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);
这是我接收通用示例缓冲区的实际代码:
/* receiving data_size */
readn(socket, &data_size, 2);
/* receiving buffer */
readn(socket, buffer, data_size);
但这不起作用,我认为是因为 writen
需要 const char *
,而我使用的是 uint16_t
...
这些电话应该如何?谢谢。
替换
writen(socket, data_size, 2, retry_on_interrupt);
来自
if (-1 == writen(socket, &data_size, sizeof data_size, 1))
{
perror("writen() failed writing size");
exit(EXIT_FAILURE);
}
并替换这一行
writen(socket, buffer, sizeof(buffer);
来自
if (-1 == writen(socket, buffer, data_size, 1))
{
perror("writen() failed writing pay-load");
exit(EXIT_FAILURE);
}
您肯定也想在阅读功能中添加error-checking!
您还想处理一个可能的 endianness (byte-order) 问题,当 sending/receiving 介于 hardware-platforms.
之间时
我一直在使用这些 read and write 函数(由@alk 提供)。
问题是我不知道如何正确发送 uint16_t data_size;
.
这是我发送通用示例缓冲区的实际代码:
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);
这是我接收通用示例缓冲区的实际代码:
/* receiving data_size */
readn(socket, &data_size, 2);
/* receiving buffer */
readn(socket, buffer, data_size);
但这不起作用,我认为是因为 writen
需要 const char *
,而我使用的是 uint16_t
...
这些电话应该如何?谢谢。
替换
writen(socket, data_size, 2, retry_on_interrupt);
来自
if (-1 == writen(socket, &data_size, sizeof data_size, 1))
{
perror("writen() failed writing size");
exit(EXIT_FAILURE);
}
并替换这一行
writen(socket, buffer, sizeof(buffer);
来自
if (-1 == writen(socket, buffer, data_size, 1))
{
perror("writen() failed writing pay-load");
exit(EXIT_FAILURE);
}
您肯定也想在阅读功能中添加error-checking!
您还想处理一个可能的 endianness (byte-order) 问题,当 sending/receiving 介于 hardware-platforms.
之间时