简单的TCP服务器无法输出到Web浏览器

我用C语言编写了一个简单的TCP客户端和服务器程序。

它在它们之间工作正常,但我有一个疑问。

如果我想从Web服务器访问TCP服务器怎么办?

我从Web服务器获得了标题,我无法write()回Web浏览器。 响应是否应该强制执行HTTP规范?

我收到以下错误

在此处输入图像描述

服务器代码:

 // Server side C program to demonstrate Socket programming #include  #include  #include  #include  #include  #include  #define PORT 8080 int main(int argc, char const *argv[]) { int server_fd, new_socket; long valread; struct sockaddr_in address; int addrlen = sizeof(address); char buffer[1024] = {0}; char *hello = "Hello from server"; // Creating socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("In socket"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons( PORT ); // Forcefully attaching socket to the port 8080 if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) { perror("In bind"); exit(EXIT_FAILURE); } if (listen(server_fd, 3) < 0) { perror("In listen"); exit(EXIT_FAILURE); } while(1) { if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) { perror("In accept"); exit(EXIT_FAILURE); } valread = read( new_socket , buffer, 1024); printf("%s\n",buffer ); write(new_socket , hello , strlen(hello)); printf("Hello message sent\n"); } return 0; } 

输出:

 GET / HTTP/1.1 Host: localhost:8080 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 DNT: 1 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Hello message sent 

问题是什么? 浏览器是否也期望来自服务器的HTTP类型响应? 由于服务器正在发送纯文本,因此Web浏览器无法显示内容。 这是Web浏览器中显示错误的原因吗?

问题是什么? 浏览器是否也期望来自服务器的HTTP类型响应? 由于服务器正在发送纯文本,因此Web浏览器无法显示内容。 这是Web浏览器中显示错误的原因吗?

是的 ,浏览器需要HTTP响应。

这是一个简单的HTTP响应:

 HTTP/1.1 200 OK Content-Type: text/plain Content-Length: 12 Hello world! 

C代码段:

 const char *hello = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\nHello world!"; 

零件说明:

HTTP/1.1指定HTTP协议版本。

200 OK就是所谓的响应状态 。 200表示没有错误。

HTTP状态代码列表(维基百科)

Content-TypeContent-Length是http标头:

  • Content-Type是指内容类型(谁会猜到?)。 text/plain表示明文。 (还有text/htmlimage/png等..)

  • Content-Length响应的总大小(以字节为单位)。