diff --git a/examples/wiznet5k_cpython_client_for_simpleserver.py b/examples/wiznet5k_cpython_client_for_simpleserver.py new file mode 100755 index 0000000..ae89d8b --- /dev/null +++ b/examples/wiznet5k_cpython_client_for_simpleserver.py @@ -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) diff --git a/examples/wiznet5k_simpleserver.py b/examples/wiznet5k_simpleserver.py index 548af79..82a2cc3 100644 --- a/examples/wiznet5k_simpleserver.py +++ b/examples/wiznet5k_simpleserver.py @@ -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")