我在 C 中有以下场景:一个简单的客户端程序向服务器发送类似 HTTP 的请求,然后服务器应该返回指定文件的输入。到目前为止,服务器应该只支持三种方法:GET、HEAD 和错误请求的默认答案。
这是服务器程序的一部分:
for(;;){
struct sockaddr_in clientAddr;
int clientAddrLen = sizeof(clientAddr);
int clientSocket;
clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen);
char buf[BUFSIZE];
int bytesRecv;
bytesRecv = recv(clientSocket, (char*)&buf, BUFSIZE, 0);
while(bytesRecv > 0){
char *method;
method = strtok(buf, " ");
printf("method %s\n", method);
if(strncmp(method, head, 4) == 0){
/*HEAD*/
char answer[] = "method: HEAD\0";
send(clientSocket, answer, sizeof(answer) + 1, 0);
}else{
if (strncmp(method, get, 3) == 0){
/*GET*/
char answer[] = "method: GET\0";
send(clientSocket, answer, sizeof(answer) + 1, 0);
}else{
/*bad request*/
char answer[] = "HTTP/1.1 400 Bad Request\0";
send(clientSocket, answer, sizeof(answer) + 1, 0);
}
}
/*Read*/
bytesRecv = recv(clientSocket, (char*)&buf, BUFSIZE, 0);
}
这是客户端程序的一部分,它要求在命令行上输入请求,然后发送相应的输入:
char* server_reply[1024];
char* msg[100];
/*send requests*/
for(;;){
printf("Request:\n");
scanf("%s", &msg);
if(strcmp(msg, "quit") == 0){
break;
}
send(clientSocket, msg, sizeof(msg), 0);
if(recv(clientSocket, server_reply, sizeof(server_reply), 0) < 0){
printf("Failure in recv.");
}else{
printf("Server: %s\n", server_reply);
}
}
现在,问题如下:当我在客户端输入例如“GET HEAD asd”时,我从服务器得到三个答案,即
方法:获取
方法:头
HTTP/1.1 400 错误请求
当它实际上应该只是“方法:GET”时。我真的不明白这种行为......感谢您的帮助!