C套接字编程中的持久连接

时间:2017-07-21 07:05:55

标签: c sockets

我编写了一个客户端代码来创建套接字并向客户端发送请求,因为HTTP 1.1使用Connection:Alive默认情况下仍然关闭连接。如何创建持久连接,以便服务器监听每个请求直到连接关闭。客户端代码是:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

void error(char *msg){
perror(msg);
exit(0);
}

int main(int argc, char *argv[])
{
 int sockfd, portno, n,i;
int Max_Requests;
struct sockaddr_in serv_addr;
struct hostent *server;

char buffer[256];
if (argc < 3) {
   fprintf(stderr,"usage %s hostname port\n", argv[0]);
   exit(0);
}
Max_Requests=atoi(argv[3]);
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);

if (sockfd < 0)
    error("ERROR opening socket");

server = gethostbyname(argv[1]);
if (server == NULL) {
    fprintf(stderr,"ERROR, no such host\n");
    exit(0);
}

bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,(char *)&serv_addr.sin_addr.s_addr,server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
    error("ERROR connecting");

i=0;
while(i<Max_Requests){
    printf("Please enter the message: ");
    bzero(buffer,256);
    fgets(buffer,255,stdin);
    n = write(sockfd,buffer,strlen(buffer));
    if (n < 0)
        error("ERROR writing to socket");

    bzero(buffer,256);
    n = read(sockfd,buffer,255);
    if (n < 0)
        error("ERROR reading from socket");

    printf("%s\n",buffer);
    i++;
}
return 0;
}

1 个答案:

答案 0 :(得分:2)

问题是您使用fgets来读取用户的输入以形成请求。

问题在于如何使用它,即读取作为请求发送到服务器的单行。然后,您立即转到read电话并等待响应,而不是发送完整请求及其标题。

这会导致服务器超时并关闭连接,因为它没有收到完整的请求。