Skip to content

Commit e2f3e1d

Browse files
committed
Add socket examples (simple HTTP client and server).
1 parent e02b2d4 commit e2f3e1d

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

examples/unix/sock-client.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
mod = rawsocket
2+
s = mod.socket()
3+
4+
if 1:
5+
ai = mod.getaddrinfo("google.com", 80)
6+
print("Address infos:", ai)
7+
addr = ai[0][4]
8+
else:
9+
# Deprecated way to construct connection address
10+
addr = mod.sockaddr_in()
11+
addr.sin_family = 2
12+
#addr.sin_addr = (0x0100 << 16) + 0x007f
13+
#addr.sin_addr = (0x7f00 << 16) + 0x0001
14+
#addr.sin_addr = mod.inet_aton("127.0.0.1")
15+
addr.sin_addr = mod.gethostbyname("google.com")
16+
addr.sin_port = mod.htons(80)
17+
18+
print("Connect address:", addr)
19+
s.connect(addr)
20+
21+
s.write("GET / HTTP/1.0\n\n")
22+
print(s.readall())

examples/unix/sock-server.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
mod = rawsocket
2+
s = mod.socket()
3+
4+
ai = mod.getaddrinfo("127.0.0.1", 8080)
5+
print("Bind address info:", ai)
6+
addr = ai[0][4]
7+
8+
s.bind(addr)
9+
s.listen(5)
10+
print("Listening, connect your browser to http://127.0.0.1:8080/")
11+
12+
counter = 0
13+
while True:
14+
res = s.accept()
15+
client_s = res[0]
16+
client_addr = res[1]
17+
print("Client address:", client_addr)
18+
print("Client socket:", client_s)
19+
print("Request:")
20+
print(client_s.read(4096))
21+
#print(client_s.readall())
22+
client_s.write("""\
23+
HTTP/1.0 200 OK
24+
25+
Hello #{} from MicroPython!
26+
""".format(counter))
27+
client_s.close()
28+
counter += 1

0 commit comments

Comments
 (0)