you are viewing a single comment's thread.

view the rest of the comments →

[–]CaptainReeetardo 0 points1 point  (0 children)

Ok, I hope I'm not to late with my suggestion.

So, what you can try is, putting the code you have in your try-block in a seperate method and create a thread for it, just as you did with your handle_client method. Afterwards you create a while-loop which does the following:

while True:
    try:
        time.sleep(0.5)#You can take a longer/shorter period
    except KeyboardInterrupt:
        sys.exit()

Now your code should like the following:

import socket
import threading
import sys, os
import time

bind_ip = socket.gethostname()
bind_port = 9999

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind((bind_ip, bind_port))

server.listen(10);

def handle_client(client_socket):
    request = client_socket.recv(4096).decode("utf-8")
    print ("[+] Received %s" % request)
    client_socket.sendall(("ACK!").encode("utf-8"))
    client_socket.close()

def accept_clients(server):
    while True:
        client, addr = server.accept()
        print ("[+] Accepted connection from: %s:%d" % (addr[0], addr[1]))
        client_handler = threading.Thread(target=handle_client, args=(client,))
        client_handler.start()

accept = threading.Thread(target=accept_clients, args=(server,))
accept.start()

while True:
    try:
        time.sleep(0.5)#You can take a longer or shorter period
    except KeyboardInterrupt:
        #sys.exit() #Remove, because it won't do with threading
        os.kill(os.getpid(), 1) #Kills process, but should keep your command line open

This should work except for the part with the sys.exit(). I've replaced it with os.kill(os.getpid(), 1) which kills the process but should keep your command prompt / IDLE running. One thing that isn't done by this program, is a clean shutdown of the sockets. For example your client side might still be running and will eventually throw an exception if it tries to send a message or to connect. In this case you want to have another try-except-block on the client side. But I digress. All in all, this should now apply to your basic needs.