首页 文章

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

提问于
浏览
1

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

问题是服务器使用unsigned char来表示数据包的大小,因为char已签名(从-128到127)而127不足以表示某些数据包中最多可达255的大小 . =>我需要一个unsigned char缓冲区;

在Linux中,recv()函数的第二个参数是void *,这意味着我可以声明一个void * buffer并且没有问题 . 但是Windows(MinGW)中的recv()有char *而不是void * . 哪个给我警告“参数类型不匹配:不兼容的指针类型'char *'和'unsigned char *'”

有可能解决这个问题吗?这是代码 . 谢谢 .

PS:我正在使用NON BLOCKING套接字 .

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);
}

1 回答

  • 2

    只需将指针强制转换为正确的类型即可 . 所以使用:

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

    另外,为什么要通过在睡眠循环中重复非阻塞操作来创建阻塞方案?使用阻塞套接字或使用非阻塞套接字,但不要在 recv 上旋转 . )

    最后,为什么在第一次调用 recv 时只读取一个字节?无论如何你还需要剩下的数据,那么为什么要让内核以微小的方式给你呢?为什么不尽可能多地读取字节数,运气好的话,避免再次调用 recv

相关问题