forked from doniks/pycom-examples
-
Notifications
You must be signed in to change notification settings - Fork 1
/
http2.py
56 lines (50 loc) · 2.04 KB
/
http2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from network import WLAN
from network import HTTP_Server
from network import HTTP_Client
# The callback that handles the responses generated from the requests sent to a HTTP/S Server
def server_callback(uri, method, headers, body, new_uri, status):
print("Request URI: {}".format(uri))
print("Request Method: {}".format(method))
for key, value in headers.items():
print("Request headers:", (key, value))
print("Request Body: {}".format(body))
print("Request New URI: {}".format(new_uri))
print("Request Status: {}".format(status))
# The callback that handles the responses generated from the requests sent to a HTTP/S Server
def client_callback(status, headers, body):
print("Response Status: {}".format(status))
for key, value in headers.items():
print("Response headers:", (key, value))
print("Response Body: {}".format(body))
# Connect to the network
wlan = WLAN(mode=WLAN.STA)
wlan.connect('Pycom', auth=(WLAN.WPA2, 'PyE!ndh0ven#'))
while not wlan.isconnected():
pass
print(wlan.ifconfig())
IP=wlan.ifconfig()[0]
# Initilise an HTTP Server
HTTP_Server.init()
# Add new resource to Server
res = HTTP_Server.add_resource('/resource', value = "Hello Client!")
# Register resource request handler
res.register_request_handler(HTTP_Server.GET, callback=server_callback)
# Initialize an HTTP Client
HTTP_Client.init('http://' + str(IP + '/resource'), callback=client_callback)
# Send request with body
HTTP_Client.send_request(body='Hello Server!')
# ```
# To implement HTTPS Server and Client, only the two init methods need to be changed. HTTP Server and Client init:
#
# ```python
# # HTTP Server init
# HTTP_Server.init()
# # HTTP Client init
# HTTP_Client.init('http://' + str(wlan.ifconfig()[0] + '/resource'), callback=client_callback)
# ```
# HTTPS Server and Client init:
# ```python
# # HTTPS Server init
# HTTP_Server.init(port=443, keyfile='/flash/cert/prvtkey.pem', certfile='/flash/cert/cacert.pem')
# # HTTPS Client init
# HTTP_Client.init('https://' + str(wlan.ifconfig()[0] + '/resource'), callback=client_callback)