由于其范围,使用 unsigned char 而不是 char

Using unsigned char instead of char because of its range

我一直在开发一个小型的纯 C 客户端应用程序(我的第一个 :/),它使用 TCP 套接字与服务器进行通信。服务器向我发送一个数据包(C 结构),其中第一个字节包含数据包的大小。

问题是服务器使用 unsigned char 来表示数据包的大小,因为 char 是有符号的(从 -128 到 +127),+127 不足以表示在某些情况下可以达到 255 的大小数据包。 => 我需要一个无符号字符缓冲区;

在Linux中,recv()函数的第二个参数是void *,也就是说我声明一个void *buffer是没有问题的。但是 Windows (MinGW) 中的 recv() 有 char * 而不是 void *。这给我警告 "Parameter type mismatch: Incompatible pointer types 'char *' and 'unsigned char *'"

这个问题可以解决吗?这是代码。谢谢

PS:我正在使用非阻塞套接字。

 int recvsize = 0;
unsigned char tmpsize;
int index = 0;
unsigned char *buffer;

while (1) {

    recvsize = recv(server, &tmpsize, sizeof(unsigned char), 0); // every packet starts with one byte where is its length

    if (recvsize > 0 ) {
         buffer = malloc(tmpsize * sizeof(unsigned char)); //memory allocation according to the size of packet
         buffer[0] = tmpsize--; //get back the size value to the buffer
         recvsize = 0;


        do { //loop over and over until you do not have all bytes of the packet
            recvsize = recv(server, &buffer[++index], tmpsize, 0);

            if (recvsize == 0)
                break;


            tmpsize -=recvsize;
            index += recvsize;

        } while (tmpsize != 0);

    }
sleep(50);
}

只需将指针转换为正确的类型。所以使用:

(char *) (&buffer[++index])

此外,为什么要通过在睡眠循环中重复非阻塞操作来创建阻塞方案?使用阻塞套接字或使用非阻塞套接字,但不要在中间创建一些假的东西。 (例如,如果恶意或慢速客户端只向您发送一个字节,您将继续 recv。)

最后,为什么在第一次调用 recv 时只读取一个字节?无论如何你都需要其余的数据,那么为什么要让内核一点一点地给你呢?为什么不尽可能多地读取字节,如果幸运的话,避免再次调用 recv