Here is an example of a server program and a client program that communicate each other over the network.
The server, once the client has received a connection from the client, attends the request by spawning a dedicated thread.
It's a very simple scheme that can help to develop a more complex python use cases that communicate over the network.
import socket
import threading
def process_connection( conn, addr ):
with conn:
print(f"connected by {addr}")
data = conn.recv( 1024 )
if data:
print(f"received: {data}")
conn.sendall( b"hello dear client" )
print(f"disconnected from {addr}")
if __name__ == '__main__':
print("hello")
config = { "main_port": 2347 }
# launch a server who will wait for calls from
# the workers UNTIL there is no more data to send
addr = ("", config["main_port"])
if socket.has_dualstack_ipv6():
sock = socket.socket( family = socket.AF_INET6 )
else:
sock = socket.socket( )
with sock:
sock.bind( addr )
sock.listen()
while True: # here we can stop when there is no more data to send to clients, by example
thread = threading.Thread( target = process_connection, args = sock.accept() )
thread.start()
import socket
if __name__ == '__main__':
print("hello")
config = { "main_port": 2347 }
addr = ("::1", config["main_port"])
if socket.has_dualstack_ipv6():
sock = socket.socket( family = socket.AF_INET6 )
else:
sock = socket.socket( )
with sock:
sock.connect( addr )
sock.sendall( b"this-is-a-test" )
data = sock.recv( 1024 )
if not data:
print( f"¿connection aborted?")
else:
print( f"received: {data}")