Abh*_*bey 2 html c sockets webserver http
我有以下C程序,该程序以HTML语法将文本写入端口5010。
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
int main(int argc, char *argv[])
{
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr;
char* sendBuff="<html><head><title>page 1</title></head></html>";
time_t ticks;
uint32_t ip = 0;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
//memset(sendBuff, '0', sizeof(sendBuff));
inet_aton("127.0.0.1", (struct in_addr*)&ip);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(ip);
serv_addr.sin_port = htons(5010);
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
listen(listenfd, 10);
while(1)
{
connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
fprintf(stderr, "New connection \n");
ticks = time(NULL);
//snprintf(sendBuff, sizeof(sendBuff), "%.24s\r\n", ctime(&ticks));
write(connfd, sendBuff, strlen(sendBuff));
close(connfd);
sleep(1);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在浏览器的地址栏中发出以下请求:
127.0.0.1:5010
Run Code Online (Sandbox Code Playgroud)
当您在浏览器栏中键入“ 127.0.0.1:5010”时,它假定另一端的服务器正在使用HTTP协议。您的浏览器将自动将URL更改为http://127.0.0.1:5010/
。这意味着另一端的服务器必须以有效的HTTP响应进行响应。
HTTP协议要求您传递的不仅仅是传递要显示的数据。例如,这是一个非常简单的网页的服务器响应:
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Connection: close
Content-Length: 89
<!DOCTYPE html>
<html><head><title>page 1</title></head><body>Hello World!</body></html>
Run Code Online (Sandbox Code Playgroud)
此外,除非您实际发送Content-Type
带有适当值的标头,否则您的浏览器无法知道将内容显示为HTML 。
有关HTTP协议的更多详细信息,您可能需要阅读相应的Wikipedia文章或实际上定义当前HTTP 1.1规范的以下6个RFC: