SoFunction
Updated on 2024-11-12

Getting started with socket programming in python

Flask or other frameworks are encapsulated more complete, we can not pay attention to routing, SESSION, etc. in the end how to achieve, and now we use sockets to achieve a To do site with registration, login function, so that the back-end framework to understand a little more in-depth (of course, you can also go directly to see the Flask source code).

The main program code is as follows:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import socket
from exts import Request
from route import response_for_request
from datetime import datetime
def run_server(host='', port=1207):
  # Create a () class s
  with () as s:
    # Set s to release ports as soon as the server is shut down to avoid Address already in use errors
    (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Bind host and port
    ((host, port))
    while 1:
      # Start listening for incoming connections, the maximum number of connections that can hang is 5.
      (5)
      # Accept connection, keep reading according to buffer_size
      connection, address = ()
      r = ''
      buffer_size = 1024
      while 1:
        data = (1024).decode('utf-8')
        r += data
        if len(data) < buffer_size:
          break
      # Prevent browsers from passing over empty requests
      if len(()) < 2:
        continue
      # The last r obtained is an http request header string, which is parsed and returned using sendall.
      request = Request(r)
      # Print time, requested method and path on each request
      print(str(())[:19], , )
      response = response_for_request(request)
      (response)
      ()
if __name__ == '__main__':
  run_server()

run_server function code for a simple description of the comments can be seen; from exts import Request: from exts import a Request class, the Request class is written for parsing the http request header, this part is very simple, in the Internet search for http request related content, you can write one, including return the path of the request header , method , each field and body part , etc., are string-related operations.

from route import response_for_request: from the import of the corresponding function, that is, pass a Request class in the previous step, return the corresponding web page content, the specific implementation will be explained in the follow-up.

It can be said that the main program has been written, the entire logic is also very simple, using sockets to listen to the connection, parsing the request, and return the content corresponding to the request. Subsequently, we only need to deal with the parsing request and response part can be, the main program can not be modified.