我用C语言写了一个简单的TCP客户端和服务器程序。
它在其中运行良好,但我有疑问。
如果我想从 Web 服务器访问 TCP 服务器怎么办?
我从 Web 服务器获取了标头,但无法write()返回 Web 浏览器。响应是否应该HTTP强制符合规范?
我收到以下错误:
服务器代码:
// Server side C program to demonstrate Socket programming
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
问题是什么?浏览器是否也期待HTTP来自服务器的类型响应?由于服务器正在发送纯文本,因此 Web 浏览器无法显示内容。这是网络浏览器中显示错误的原因吗?
问题是什么?浏览器是否也期待来自服务器的 HTTP 类型响应?由于服务器正在发送纯文本,因此 Web 浏览器无法显示内容。这是网络浏览器中显示错误的原因吗?
是的,浏览器需要一个 HTTP 响应。
这是一个简单的 HTTP 响应:
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 12
Hello world!
Run Code Online (Sandbox Code Playgroud)
C 代码片段:
const char *hello = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\nHello world!";
Run Code Online (Sandbox Code Playgroud)
部分说明:
HTTP/1.1 指定 HTTP 协议版本。
200 OK就是所谓的响应状态。200 表示没有错误。
Content-Type并且Content-Length是 http 标头:
Content-Type指的是内容类型(谁会猜到?)。text/plain表示明文。(还有text/html,image/png等等。)
Content-Length 响应的总大小(以字节为单位)。
| 归档时间: |
|
| 查看次数: |
380 次 |
| 最近记录: |