Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions examples/wiznet5k_cpython_client_for_simpleserver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# SPDX-FileCopyrightText: 2023 ladyada
#
# SPDX-License-Identifier: MIT
#!/usr/bin/env python3

"""
This example client runs on CPython and connects to / sends data to the
simpleserver example.
"""
import socket
import time

print("A simple client for the wiznet5k_simpleserver.py example in this directory")
print(
"Run this on any device connected to the same network as the server, after "
"editing this script with the correct HOST & PORT\n"
)
# Or, use any TCP-based client that can easily send 1024 bytes. For example:
# python -c 'print("1234"*256)' | nc 192.168.10.1 50007


# edit host and port to match server
HOST = "192.168.10.1"
PORT = 50007
TIMEOUT = 10
INTERVAL = 5
MAXBUF = 1024

while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TIMEOUT)
print(f"Connecting to {HOST}:{PORT}")
s.connect((HOST, PORT))
# wiznet5k_simpleserver.py wants exactly 1024 bytes
size = s.send(b"A5" * 512)
print("Sent", size, "bytes")
buf = s.recv(MAXBUF)
print("Received", buf)
s.close()
time.sleep(INTERVAL)
9 changes: 6 additions & 3 deletions examples/wiznet5k_simpleserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,23 @@
spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)

# Initialize ethernet interface
eth = WIZNET5K(spi_bus, cs, is_dhcp=False)
eth = WIZNET5K(spi_bus, cs, is_dhcp=True)

# Initialize a socket for our server
socket.set_interface(eth)
server = socket.socket() # Allocate socket for the server
server_ip = "192.168.10.1" # IP address of server
server_ip = eth.pretty_ip(eth.ip_address) # IP address of server
server_port = 50007 # Port to listen on
server.bind((server_ip, server_port)) # Bind to IP and Port
server.listen() # Begin listening for incoming clients

conn, addr = server.accept() # Wait for a connection from a client.
while True:
print(f"Accepting connections on {server_ip}:{server_port}")
conn, addr = server.accept() # Wait for a connection from a client.
print(f"Connection accepted from {addr}, reading exactly 1024 bytes from client")
with conn:
data = conn.recv(1024)
if data: # Wait for receiving data
print(data)
conn.send(data) # Echo message back to client
print("Connection closed")