From aeffb64aa8886153284d5e7020f8b6bb99732d9b Mon Sep 17 00:00:00 2001 From: gijsio <67470426+gijsio@users.noreply.github.com> Date: Mon, 20 Jul 2020 13:59:39 +0200 Subject: [PATCH] included http webserver example --- .../tutorials/networkprotecols/webserver.md | 69 ++++++++++++++++--- 1 file changed, 60 insertions(+), 9 deletions(-) diff --git a/content/tutorials/networkprotecols/webserver.md b/content/tutorials/networkprotecols/webserver.md index 4e8a411..6bd67da 100644 --- a/content/tutorials/networkprotecols/webserver.md +++ b/content/tutorials/networkprotecols/webserver.md @@ -6,26 +6,77 @@ aliases: - chapter/tutorials/networks/webserver --- -Using the WiFi connection, we can create a simple webserver on the module +Using the WiFi connection, we can create a HTTP simple webserver on the module with the socket library. ```python +import usocket +import _thread +import time from network import WLAN -import socket +import pycom -wlan = WLAN() -wlan.init(mode=WLAN.STA, ssid="", auth=(WLAN.WPA2, "")) #you can use both STA or AP mode for the webserver +availablecolor = 0x001100 +connectioncolor = 0x110000 -sock = socket.socket(usocket.AF_INET, usocket.SOCK_STREAM) #use the socket on the WLAN (INET) adapter, and use stream (TCP) -sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #set the options to use IP addresses, and check the default option to reuse. -sock.bind(("192.168.4.1"), 80) #use the socket on this ip address, using this port. Change the IP address if you are using STA mode. +# Thread for handling a client +def client_thread(clientsocket,n): + # Receive maxium of 12 bytes from the client + r = clientsocket.recv(4096) -sock.listen(5) #allow for 5 simultaneous connections + # If recv() returns with 0 the other end closed the connection + if len(r) == 0: + clientsocket.close() + return + else: + # Do something wth the received data... + print("Received: {}".format(str(r))) #uncomment this line to view the HTTP request + http = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection:close \r\n\r\n" #HTTP response + + if "GET / " in str(r): + #this is a get response for the page + # Sends back some data + clientsocket.send(http + "