c - 写入n个字节并读取n个字节: sending number of bytes to read using uint16_t

标签 c sockets tcp stdint

我一直在使用这些readwrite函数(由@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);
}
<小时/>

您肯定也想在阅读功能中添加错误检查!

<小时/>

您还想处理可能的 endianness (byte-order)在不同硬件平台之间发送/接收时出现问题。

关于c - 写入n个字节并读取n个字节: sending number of bytes to read using uint16_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41662862/

相关文章:

java - notifyAll() 不起作用,如何在套接字编程中通知所有线程

sockets - 如何从给定套接字读取协议(protocol)信息?

java - 套接字批量读取返回一个零数组

c - scanf ("%[^:]]", word) 如何在 C 中工作

android - 正确路由非互联网 Wifi 套接字和蜂窝互联网请求 (Android L & M)

c - malloc 一个 char 和 null 终止符

python - ssl.SSLError : [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed, Python 套接字、ssl、gmail smtp 连接

我可以在主应用程序和多个线程中使用相同的套接字吗?

c - 将文件放入链接列表时出现空格

c++ - std::locale 没有 lconv::p_cs_precedes 的等价物?