我编写了一个服务器,当浏览器尝试连接到某些站点时,它会检查黑名单并发回 404,但是当我调用 send() 时没有错误,但消息不会出现在网络上浏览器,除非我关闭连接?
有什么建议吗?
接受来自浏览器的连接
while(1){
connfd = accept(fd, (struct sockaddr *) &cliaddr, &cliaddrlen);
if (connfd == -1) {
perror ("unable to accept");
return 1;
}
printf("%s:%d connected\n", inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port));
printf("%d",threadIndex);
pthread_create(&(thread[threadIndex++]), NULL, processRequests, (void *)connfd);
}
处理请求方法发送片段:
if(blacklisted ==1){
printf("is blacklisted\n");
char *response404 = "HTTP:/1.1 404 not avaliable\r\n\r\n";
printf("%s\n",response404);
int len, bytes_sent;
len = strlen(response404);
bytes_sent = send(connfd, response404, len, 0);
if(len != bytes_sent){
perror("message length doesn't match");
}
}
最佳答案
浏览器在解析和显示页面之前等待连接关闭。
没有办法解决。
in HTTP/0.9 and 1.0, the connection is closed after a single request/response pair.
In HTTP/1.1 a keep-alive-mechanism was introduced, where a connection could be reused for more than one request.
注意:Keepalive 技术在这里没有用处,因为您要为每个连接到特定位置的客户端发送一个页面。
关于C套接字编程,发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9458489/