Python – How do I break socket.recv() in python?

How do I break socket.recv() in python?… here is a solution to the problem.

How do I break socket.recv() in python?

I’m working on a small server system and whenever I type “exit()” in the console I need to shut down the server (input is handled from another thread)
I was wondering if there was a way to terminate the main thread while the socket waited for data. I’ve tried using _thread.interrupt_main() and the keyboardInterrupt exception in try block, but it doesn’t work.
I also tried os._exit() but it didn’t clean up, so I decided not to use it.
My code:

import socket
import _thread
import os

clear = lambda: os.system("cls")

try:
    Server = socket.socket(socket.AF_INET,socket. SOCK_STREAM)
    Server.bind(("localhost",port))
    Server.listen(2)
    clear()
    print("--------------------------------------")
    print("Server running on port %s" % str(port))
    print("--------------------------------------")
except Exception:
    print("error while starting server")
    input()
    exit()

def control():
    while True:
        command = input()
        if command == "exit()":
            #interrupt code here

_thread.start_new_thread(control,())

while True:
    con,ip = Server.accept()
    print(str(ip) + " Connected")

try:
        cmd = str(con.recv(1024).decode())  #<-- interrupt this line
    except Exception:
        print("Error")

Solution

sock.shutdown(socket. SHUT_RDWR) Very handy if you have a socket in the main thread and that thread is blocked in recv/recvfrom/etc. The recv call will end with an exception and you can use it to complete your thread if needed.

Related Problems and Solutions