The design of Python Web server

Source: Internet
Author: User

1. Use Python to write a static Web server that can handle HTTP requests for static pages

Principle:

A. Using the socket for communication between the server and the browser

B. Using multithreading to handle requests from multiple client browsers

C. Sending response data using the HTTP protocol

Realize:

# coding:utf-8import socketfrom multiprocessing import processdef handle_request (client_socket):    request_data = CLIENT_SOCKET.RECV (1024x768)    response_first_line = "http/1.1 ok\r\n"    response_headers = "Server:my Web Static server\r\n "    response_body =" Hello, My Web Static Server "    response = response_first_line + response_headers +" \r\ N "+ response_body    client_socket.send (bytes (response, encoding=" UTF-8 "))    client_socket.close () If __name__ = = "__main__":    server_socket = Socket.socket (socket.af_inet, socket. SOCK_STREAM)    Server_socket.bind (("", 8001)) Server_socket.listen (+) while    True:        client_ Socket, client_address = server_socket.accept ()        print (' ['%s ', '%s '] user already connected to the server! '% client_address)        handler = Process (Target=handle_request, args= (Client_socket,))        Handler.start ()        Client_socket.close ()

  

The design of Python Web server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.