Skip to content

Commit f71584b

Browse files
authored
Merge pull request #88 from e28eta/patch-1
Update SimpleServer example to accept >1 connection
2 parents 60e55dd + 8ea6a17 commit f71584b

File tree

2 files changed

+46
-3
lines changed

2 files changed

+46
-3
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# SPDX-FileCopyrightText: 2023 ladyada
2+
#
3+
# SPDX-License-Identifier: MIT
4+
#!/usr/bin/env python3
5+
6+
"""
7+
This example client runs on CPython and connects to / sends data to the
8+
simpleserver example.
9+
"""
10+
import socket
11+
import time
12+
13+
print("A simple client for the wiznet5k_simpleserver.py example in this directory")
14+
print(
15+
"Run this on any device connected to the same network as the server, after "
16+
"editing this script with the correct HOST & PORT\n"
17+
)
18+
# Or, use any TCP-based client that can easily send 1024 bytes. For example:
19+
# python -c 'print("1234"*256)' | nc 192.168.10.1 50007
20+
21+
22+
# edit host and port to match server
23+
HOST = "192.168.10.1"
24+
PORT = 50007
25+
TIMEOUT = 10
26+
INTERVAL = 5
27+
MAXBUF = 1024
28+
29+
while True:
30+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
31+
s.settimeout(TIMEOUT)
32+
print(f"Connecting to {HOST}:{PORT}")
33+
s.connect((HOST, PORT))
34+
# wiznet5k_simpleserver.py wants exactly 1024 bytes
35+
size = s.send(b"A5" * 512)
36+
print("Sent", size, "bytes")
37+
buf = s.recv(MAXBUF)
38+
print("Received", buf)
39+
s.close()
40+
time.sleep(INTERVAL)

examples/wiznet5k_simpleserver.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,23 @@
1818
spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
1919

2020
# Initialize ethernet interface
21-
eth = WIZNET5K(spi_bus, cs, is_dhcp=False)
21+
eth = WIZNET5K(spi_bus, cs, is_dhcp=True)
2222

2323
# Initialize a socket for our server
2424
socket.set_interface(eth)
2525
server = socket.socket() # Allocate socket for the server
26-
server_ip = "192.168.10.1" # IP address of server
26+
server_ip = eth.pretty_ip(eth.ip_address) # IP address of server
2727
server_port = 50007 # Port to listen on
2828
server.bind((server_ip, server_port)) # Bind to IP and Port
2929
server.listen() # Begin listening for incoming clients
3030

31-
conn, addr = server.accept() # Wait for a connection from a client.
3231
while True:
32+
print(f"Accepting connections on {server_ip}:{server_port}")
33+
conn, addr = server.accept() # Wait for a connection from a client.
34+
print(f"Connection accepted from {addr}, reading exactly 1024 bytes from client")
3335
with conn:
3436
data = conn.recv(1024)
3537
if data: # Wait for receiving data
3638
print(data)
3739
conn.send(data) # Echo message back to client
40+
print("Connection closed")

0 commit comments

Comments
 (0)