zoukankan      html  css  js  c++  java
  • Linux 环境 HTTP 服务器

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <netinet/in.h>
    #include <sys/socket.h>
    
    #define BUF_LEN 1028 // 1028 ever
    #define PORT 8000
    const static char html_re_hd_su[] = "HTTP/1.1 200 OK
    Content-type: text/html
    
    "; //html response header : success
    
    int CreatTcpSocket_fd(){
    	int socket_fd;
    	struct sockaddr_in address;
    	socket_fd = socket(AF_INET, SOCK_STREAM, 0); //tcp protocal
    	//catch up exception
    	if(socket_fd < 0){
    		printf("socket creation failed
    ");
    		exit(1); // 1 means exit with exception
    		return 1;
    	}
    
    	//step 2: bind the socket file description
    	memset(&address, 0, sizeof(address));
    	address.sin_family = AF_INET; //Internet protocal
    	address.sin_port = htons(PORT);
    	address.sin_addr.s_addr = INADDR_ANY; //set the host ip
    	if(bind(socket_fd, (struct sockaddr*)&address, sizeof(struct sockaddr_in))){
    		//catch up exception
    		printf("socket binding failed!
    ");
    		exit(1);
    		return 1;
    	}
    	return socket_fd;
    }
    
    void AnalyseTcpRequest(const int socket_fd){
    	char requestMessage[BUF_LEN];
    	read(socket_fd, requestMessage, BUF_LEN);
    	printf("%s
    ", requestMessage);
    }
    
    void ReplyTcpRequest(int socket_fd){
    	char replyMessage[]=
    		"<html><head><title>Welcome!</title></head>"  
    		"<body><h1>Welcome to Feng YuBo HTTP server demo!</h1>"  
    		"<p>This is a just small test page.</p></body></html>";  
    
    	write(socket_fd, html_re_hd_su, strlen(html_re_hd_su));
    	write(socket_fd, replyMessage, strlen(replyMessage));
    	printf("replyed...
    ");
    }
    
    int main(){
    	int socket_fd = CreatTcpSocket_fd();
    	listen(socket_fd, 5); //max conection number is 5 now.
    	
    	//step 3: begin to accept tcp request
    	struct sockaddr_in their_address;
    	int their_sin_len = sizeof(struct sockaddr_in);
    	
    	for ( ; ; )
    	{	
    		printf("begin to accept tcp request...
    ");
    		//begin to block the processing
    		int newSocket_fd = accept(socket_fd, (struct sockaddr*)&their_address, &their_sin_len);
    		printf("analysing...
    ");
    		AnalyseTcpRequest(newSocket_fd);
    		ReplyTcpRequest(newSocket_fd);
    		close(newSocket_fd);
    	}
    
    	exit(0);
    	return 0;
    }
    

     目标: 1.接收HTTP请求  2.打印HTTP请求报文  3.返回HTTP响应报文  4.返回预设好的网页

  • 相关阅读:
    用Python完成一个汇率转换器
    鸿蒙如何用JS开发智能手表App
    鸿蒙如何用JS开发智能手表App
    SAP Spartacus SplitViewComponent Migration 的一个具体例子
    SAP Spartacus B2B 页面 Popover Component 的条件显示逻辑
    SAP Spartacus 升级时关于 schematics 的更新
    SAP Spartacus B2B 页面 Disable 按钮的显示原理
    SAP Spartacus B2B 页面 Disable Confirmation 对话框的显示原理
    通过 Feature Level 动态控制 SAP Spartacus 的页面显示
    SAP Commerce Cloud Build Manifest Components
  • 原文地址:https://www.cnblogs.com/fengyubo/p/5596332.html
Copyright © 2011-2022 走看看