C语言 即使我遵循所有约定,Recv仍然挂起?



我正在尝试创建一个小程序,通过stdin接收http请求并将其发送到服务器。这是我使用的代码:

int portno =        3000;
char *message = buf;
char response[4096];
int byte_count;
fsize = strlen(message);
int sockfd;
/* fill in the parameters */
printf("Request:n%sn",message);
/* create the socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error("ERROR opening socket");
int sz = (1024 * 1024);
if (setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sz, sizeof(sz)) == -1) {
perror("setsockopt");
exit(1);
}
struct sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_port = htons(portno);
saddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(sockfd, &saddr, sizeof(saddr)) == -1) {
perror("connect");
}
send(sockfd, message, fsize, MSG_NOSIGNAL);
printf("written");
byte_count = recv(sockfd,response,sizeof(response)-1,0); // <-- -1 to leave room for a null terminator
response[byte_count] = 0; // <-- add the null terminator
printf("recv()'d %d bytes of data in bufn",byte_count);
printf("%s",response);
close(sockfd);

等于这个

GET /alias%2Findex.html HTTP/1.0rn
rn
rn
rn

我通过其他堆栈溢出文章做了一些研究,他们说recv通常在系统等待响应时挂起。我不知道是什么原因造成的。

这是您的程序仅稍加修改。这对我很有效。您确定在本地主机端口3000上运行的任何服务器都能正确响应吗?顺便说一句,我不得不为我的系统将端口更改为8080。

#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
char buf[1 << 16] = "GET /file.txt HTTP/1.0rn"
"rn"
"rn";
int main() {
int portno = 8080;
char *message = buf;
int byte_count;
int fsize = strlen(message);
int sockfd;
/* fill in the parameters */
printf("Request:n%sn", message);
/* create the socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
perror("ERROR opening socket");
int sz = (1024 * 1024);
if (setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sz, sizeof(sz)) == -1) {
perror("setsockopt");
exit(1);
}
struct sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_port = htons(portno);
saddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) == -1) {
perror("connect");
}
send(sockfd, message, fsize, MSG_NOSIGNAL);
printf("written");
while ((byte_count = recv(sockfd, buf, sizeof(buf) - 1, 0)) >
0) {            // <-- -1 to leave room for a null terminator
buf[byte_count] = 0; // <-- add the null terminator
printf("recv()'d %d bytes of data in bufn", byte_count);
printf("%s", buf);
}
close(sockfd);
return 0;
}

最新更新