Python server daemon not working

1k views Asked by At

I need to make a basic python server run as a daemon but when I set the thread to run as a daemon, the socket doesnt listen anymore. I try to connect to it with a client to send a file to it but I get a connection error. When I leave out the part that sets it to a daemon, it works just fine. Suggestions? Thanks

Server code:

import socket
import sys
import threading

HOST = "localhost"
PORT = 3000
exit = False

def handle_client(client):
    global exit
    filename = client.recv(50).decode()
    client.send(b"/ok")

    if filename == '':
        client.close()

        return
    elif filename == '/kill':
        exit = True
        client.send(b'killing server...\n')

        killserver = socket.socket()
        killserver.connect((HOST, PORT))
        killserver.close()

        client.send(b'success.\n')
        client.close()

        return

    f = open(filename, "wb")

    data = client.recv(1024)
    while(data):
        f.write(data)
        data = client.recv(1024)
    f.close()

    print("Wrote file " + filename)

    client.close()

def server():
    servsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    servsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    servsock.bind((HOST,PORT))

    print("[INFO]: listening on " + str(PORT))
    servsock.listen(10)

    while True:
        client, addr = servsock.accept()

        if exit is True:
            print("[INFO]: server received kill request")
            break

        print("[INFO]: connection from " + addr[0])

        hc = threading.Thread(target=handle_client, args=(client,))
        hc.start()

    servsock.close()

s = threading.Thread(target=server)
s.setDaemon(True)
s.start()
1

There are 1 answers

4
Mark Tolonen On BEST ANSWER

When there are only daemon threads running, the process exits. After you start the thread, you exit the main thread. You don't want the server thread to be daemonic.