Skip to content

Commit d991da7

Browse files
committed
socket-client, socket-server examples now run on both Micro- and C-Python.
1 parent a80ff04 commit d991da7

File tree

2 files changed

+42
-20
lines changed

2 files changed

+42
-20
lines changed

examples/unix/sock-client.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,32 @@
1-
mod = rawsocket
2-
s = mod.socket()
1+
try:
2+
import rawsocket as _socket
3+
except:
4+
import _socket
5+
6+
7+
s = _socket.socket()
38

49
if 1:
5-
ai = mod.getaddrinfo("google.com", 80)
10+
ai = _socket.getaddrinfo("google.com", 80)
611
print("Address infos:", ai)
712
addr = ai[0][4]
813
else:
9-
# Deprecated way to construct connection address
10-
addr = mod.sockaddr_in()
14+
# Deprecated ways to construct connection address
15+
addr = _socket.sockaddr_in()
1116
addr.sin_family = 2
1217
#addr.sin_addr = (0x0100 << 16) + 0x007f
1318
#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)
19+
#addr.sin_addr = _socket.inet_aton("127.0.0.1")
20+
addr.sin_addr = _socket.gethostbyname("google.com")
21+
addr.sin_port = _socket.htons(80)
1722

1823
print("Connect address:", addr)
1924
s.connect(addr)
2025

21-
s.write("GET / HTTP/1.0\n\n")
22-
print(s.readall())
26+
if 0:
27+
# MicroPython rawsocket module supports file interface directly
28+
s.write("GET / HTTP/1.0\n\n")
29+
print(s.readall())
30+
else:
31+
s.send(b"GET / HTTP/1.0\n\n")
32+
print(s.recv(4096))

examples/unix/sock-server.py

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,18 @@
1-
mod = rawsocket
2-
s = mod.socket()
1+
try:
2+
import rawsocket as socket
3+
except:
4+
import socket
35

4-
ai = mod.getaddrinfo("127.0.0.1", 8080)
6+
7+
CONTENT = """\
8+
HTTP/1.0 200 OK
9+
10+
Hello #{} from MicroPython!
11+
"""
12+
13+
s = socket.socket()
14+
15+
ai = socket.getaddrinfo("127.0.0.1", 8080)
516
print("Bind address info:", ai)
617
addr = ai[0][4]
718

@@ -17,12 +28,13 @@
1728
print("Client address:", client_addr)
1829
print("Client socket:", client_s)
1930
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))
31+
if 0:
32+
# MicroPython rawsocket module supports file interface directly
33+
print(client_s.read(4096))
34+
#print(client_s.readall())
35+
client_s.write(CONTENT.format(counter))
36+
else:
37+
print(client_s.recv(4096))
38+
client_s.send(bytes(CONTENT.format(counter), "ascii"))
2739
client_s.close()
2840
counter += 1

0 commit comments

Comments
 (0)