Ideas :
1、 Create a listening socket
2、 Binding local IP and port Information
3、 Use listen Change monitoring status
4、 Receive the server link , Create a client socket to serve the client
5、 Get the information sent by the server
6、 Use regular expressions to match the information sent by the client , Get the information needed by the server
7、 According to the match , Operate locally
8、 Send the matched local resources to the client
9、 close Client socket , End of service , Wait for the next client link .
Dependent resources :
1、socket、re package
2、 Create it yourself or put it in the same directory img.html and 3.pdf( You can replace it with the content you want to display in the browser )
3、 One named favicon The format is ico Pictures of the , Because the browser will take this picture by default when visiting the website , The icon displayed in the upper left corner of the browser label .
Code up :
from socket import *
import re
def client_sever(new_socket):
# 5、 Get the information sent by the server , And set the received data byte size
request=new_socket.recv(1024).decode('utf-8')
# 6、 Use regular expressions to match the information sent by the client , Get the information needed by the server , The matching resource address
g=re.match(r'[^/]*/+([^ ]*)\s+',request)
file_name=g.group(1)
# 7、 According to the match , Operate locally
# Open local resource , Read the local data as the response body
try: # Execute code
with open(file_name,'rb') as f:
response_body=f.read()
except: # Execute when an exception occurs
response_body = '<h1>hello world!</h1>'.encode('utf-8')
finally: # Whether there is any abnormality , Code that will execute
response_header = 'HTTP/1.1\r\n'
response_header += '\r\n'
print(file_name)
# Assemble local data
response = response_header.encode('utf-8') + response_body
# 8、 Send the matched local resources to the client
new_socket.send(response)
# 9、 Close client socket , End of service , Wait for the next client link .
new_socket.close()
def main():
# 1、 Create a listening socket
server_socket=socket(AF_INET,SOCK_STREAM)
#server_socket.setblocking(False)
# 2、 Binding local IP and port Information , Local information is in tuple format
server_socket.bind(('',8080))
# 3、 Use listen Change monitoring status , Set listening capacity
server_socket.listen(128)
while True:
# 4、 Receive the server link , Create a client socket to serve the client
new_socket, client_addr = server_socket.accept()
# Call function methods to serve the client
client_sever(new_socket)
if __name__ == '__main__':
main()
Be careful :http The protocol header is in text form , With \r\n As a separator for each field , Finally, the head with two \r\n end , So we mainly construct http head , The browser can recognize the next text