Purpose of the experiment:Use socket to simulate a miniature web server, when the py script runs, the real miniature web server set up, and then use the local browser to access 127.0.0.1:8080 (web server's ip_port) when the web server will pass the content of the web page to the browser to realize the web page to browse.
sw+sys: python3.7.2 + windows10 64bit
The locally prepared server-side web page is the downloaded hao123 homepage (I have uploaded and uploaded it.).Click here)
I learned through this experiment:
1. When get requests a home page, to display a complete page (including text, images, css coloring, etc.) is to get multiple requests.
2. respone replies to the local page network, open(filepath, rwa) should pay special attention to the
import socket import os curfilepath = ((__file__))[0].replace("\\" , "/") print(f'curfilepath: {curfilepath}') def new_socket_server(new_socket, new_addr): if new_addr[0] != '': print(f'Current Client{new_addr}connectedserverextremity. ') # 3. Receive information file_name = '' request_data = new_socket.recv(1024).decode('utf-8') if request_data != '': print(f'I'm getting new information.,The information is as follows:\n{request_data}') file_name = request_data.splitlines()[0].split(' ')[1] print(f'file_name: {file_name}') if file_name == '/': file_name = '/' print(f'file_name: {file_name}') with open(curfilepath + '/', 'a+') as f: (file_name + '\n') # 4. Responding to messages try: f = open(curfilepath + '/htmltest' + file_name, 'rb') except: response = 'HTTP/1.1 404 NOT FOUND\r\n' response += '\r\n' response += '----------file not found-------' new_socket.send(('utf-8')) else: html_content = () () response = 'HTTP/1.1 200 OK\r\n' + '\r\n' new_socket.send(('utf-8')) new_socket.send(html_content) def main(): # 1. Create a socket tcp_server_socket = (socket.AF_INET, socket.SOCK_STREAM) # 2. Connect to the server server_ip_port = ('127.0.0.1', 8080) tcp_server_socket.bind(server_ip_port) tcp_server_socket.listen(128) while True: print('Waiting for client side to connect... ...') new_socket, new_addr = tcp_server_socket.accept() new_socket_server(new_socket, new_addr) new_socket.close() if __name__ == '__main__': main()
This is the whole content of this article.