You can update your script like the following:
Code:
import usocket as socketimport network# Set up WiFi connectionssid = 'name'password = 'pass'station = network.WLAN(network.STA_IF)station.active(True)station.connect(ssid, password)print(station.ifconfig()[0])# Wait until connected to WiFiwhile not station.isconnected(): pass# Define function to handle HTTP requestsdef handle_request(client_socket): request = client_socket.recv(1024) print("Request:") print(request) # Parse the request to get the requested file try: request_str = str(request, 'utf-8') request_file = request_str.split()[1][1:] # Check if the requested file exists if request_file == "": request_file = "index.html" with open(request_file, "r") as f: content = f.read() content_type = "text/html" if request_file.endswith(".html") else "text/plain" # Adjust content type based on file extension # Send HTTP response with status 200 (OK) and appropriate content type response = "HTTP/1.1 200 OK\r\n" response += f"Content-Type: {content_type}\r\n\r\n" response += content except OSError: # Handle file not found error response = "HTTP/1.1 404 Not Found\r\n" response += "Content-Type: text/plain\r\n\r\n" response += "404 Not Found" # Encode response as bytes and send it client_socket.send(response.encode('utf-8')) client_socket.close()# Create sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.bind(('0.0.0.0', 80))s.listen(5)print("Server started")# Accept incoming connections and handle requestswhile True: client, addr = s.accept() print('Got a connection from %s' % str(addr)) handle_request(client)
Statistics: Posted by barshatriplee — Thu May 09, 2024 6:15 am