skip to Main Content

enter image description hereI’ve been trying to write a server-client based project in python, here’s the code of my server.py:

#! /usr/bin/env python3 
import sys, struct, socket, threading, logging


# create a server socket that connects to 127.0.0.1 on port 512583

HOST = "127.0.0.1"
PORT = 52583
MSGLEN = 2048

def recv_all(conn,n):
  chunks = b''
  bytes_recd = 0
  while bytes_recd < n:
    chunk = conn.recv(min(n - bytes_recd, 1024))
    #if len(chunk) == 0:
    #  raise RuntimeError("socket connection broken")
    chunks += chunk
    bytes_recd = bytes_recd + len(chunk)
  return chunks

def handle_client(conn, addr):
    
    print(f"Contacted by {addr}")

    with conn:
        
        while True:
            
            data = recv_all(conn, 4)
            print("test")
            print(f"Length",len(data))
            input = struct.unpack("!i", data)[0]
            print(f"Received", input)
            if not data:
                break
            conn.sendall(struct.pack("!i",input))
            print(f"Sent", input)
                                     
def main(host=HOST, port=PORT):

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:

        try:
            s.bind((host, port))
            s.listen()
            print(f"Server listening on {host}:{port}")
            #logging.basicConfig(filename= 'server.log' , level=logging.INFO, format='%(asctime)s - %(message)s')

            while True:
                print("Waiting for a connection...")
                conn, addr = s.accept()  
                             
                client_thread = threading.Thread(target=handle_client, args=(conn, addr))
                client_thread.start()

        except KeyboardInterrupt:
            pass
        print("Server shutting down")
        s.shutdown(socket.SHUT_RDWR)
        sys.exit(1)
        
        
        


if __name__ == "__main__":
    main()

unfortunately when I try to close it from the terminal "Server shutting down" appears but it doesn’t really close. Can somebody help me?
Thanks a lot

Also if I press again Ctrl+C it gives this:

2

Answers


  1. Remove the word pass. Then correctly indent the code under the except.

    Login or Signup to reply.
  2. Your handle_client function is blocking (there is a while loop that never ends). sys.exit is waiting for that thread to end.

    You need to end the thread yourself. I think most servers do this by closing when all clients disconnect. So you’d close the handle_client thread when that client disconnects. (Or you could just kill it on Ctrl-C, but that could be a bad idea (read: corruption))

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search