Python服务器守护程序无法正常工作

时间:2015-06-21 04:10:55

标签: python sockets server daemon

我需要将一个基本的python服务器作为守护进程运行但是当我将该线程设置为守护进程时,套接字不再监听。我尝试连接到它与客户端发送文件,但我收到连接错误。当我遗漏将它设置为守护进程的部分时,它可以正常工作。建议?感谢

服务器代码:

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 个答案:

答案 0 :(得分:0)

当只有守护程序线程运行时,进程退出。启动线程后,退出主线程。您不希望服务器线程成为守护进程。