我正在用C创建一个迷你网络服务器。
以下函数应该从客户端计算机读入数据。
目标是在第一个空格之后读取第二个数据。每条输入数据都是空格分隔的。
例如,如果传入的数据是:
GET / 123/456
然后我期待/ 123/456。
如果传入的数据是:
GET / 123/456 789
然后我仍然期待/ 123/456。
此相关片段来自外部函数,该函数设置10 KB缓冲区并调用有问题的函数:
//nsock is a valid socket handle from an accept() call.
printf("CLIENT CONNECTION!\n");
char req[10000];long reqsz=10000;
getreq(req,&reqsz,nsock);
printf("Received %d bytes\n",reqsz);
printf("Data: %s\n",req);
“客户端连接!”出现在屏幕上,但如果函数内的bufsize值很高,则不会显示“已接收”。如果我将它设置为16或100之类的低值,那么一切都会正确显示。为什么像5000这样的大数字不起作用?
这是有问题的功能:
//getreq params in: req=external buffer for data
// reqsz=size of external buffer. I set 10000
// nsock=valid socket pointer from accept()
//
//getreq params out: reqsz=actual size of data returned
// req=actual data
//
void getreq(char* req,unsigned long *reqsz,long nsock){
//bufsize=how many bytes to read at once. High values like 5000 cause a stall.
//buffer=buffer of data from recv call
const unsigned long ibs=*reqsz,bufsize=5000;
char buffer[ibs],*rp=req;
//spacect=# of spaces in data read
//szct=iterator variable
//mysz=total length of returned data
//bufct=buffer counter to prevent segfault
//recvsz=data size returned from recv or
// forced -2 if buffer hits capacity
// or 2nd space in returned data is found
unsigned long spacect=0,szct=0,mysz=0,bufct=0;
long recvsz=1;char *p=buffer;
//
//Expected data: GET /whatever HTTP/x.x but we
// want /whatever
//
//loop until 2nd space is found or
//ibs bytes of data have been processed
while (recvsz > 0 && bufct < ibs){
recvsz=recv(nsock, p, bufsize, 0);
if (recvsz < 1){break;}
for (szct=1;szct<=recvsz;szct++){
if (*p==' '){spacect++;if (spacect > 2){spacect=2;recvsz=-2;break;}}
if (spacect==1 && *p != ' '){mysz++;if (mysz <= *reqsz){*rp++=*p;}}
p++;bufct++;if (bufct > ibs){recvsz=-2;break;}
}
}
// Process rest of data to try to avoid client errors
while (recvsz == -2){
recvsz=recv(nsock, buffer, bufsize, 0);
}
*reqsz=mysz;
}