我一直在开发一个小型的纯C客户端应用程序(我的第一个:/),它使用TCP套接字与服务器通信。服务器发送给我一个数据包(C结构),其中第一个字节包含数据包的大小。
问题是服务器使用unsigned char来表示数据包的大小,因为char是有符号的(从-128到+127),而+127不足以表示某些数据包中可以高达255的大小。我需要一个unsigned char buffer;
在Linux中,recv()函数的第二个参数是void *,这意味着我可以声明一个void *缓冲区,没有问题。但是Windows (MinGW)中的recv()有char *而不是void *。这给了我警告"参数类型不匹配:不兼容的指针类型'char *'和'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
第二次?