Skip to content

Instantly share code, notes, and snippets.

@rlunaro
Created November 22, 2024 07:39
Show Gist options
  • Save rlunaro/c9fcc79098f2841a828038850f6149bc to your computer and use it in GitHub Desktop.
Save rlunaro/c9fcc79098f2841a828038850f6149bc to your computer and use it in GitHub Desktop.
Server and client on python

Server and Client on python

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.

The server

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()

The client

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}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment