套接字服务器开始侦听套接字客户端连接python后,应用程序冻结

时间:2019-04-30 08:05:35

标签: python-3.x sockets

启动服务器后,应用程序挂起,但套接字服务器已正确创建。因此,无论何时执行客户端,服务器响应都正确。为什么应用程序挂起?这是示例代码

开始按钮-触发按钮

ui.button.clicked.connect(start_server) # Button to start the process

服务器套接字,在这里我为所有连接到服务器的客户端创建了一个线程,然后服务器会将其广播给客户端

def start_server():
    host = "192.168.8.241"
    port = 1024
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    print("Socket created")
    try:
        soc.bind((host, port))
    except:
        print("Bind failed. Error : " + str(sys.exc_info()))
        sys.exit()
    soc.listen(5)
    print("Socket now listening")
    while True:
        connection, address = soc.accept()
        ip, port = soc.getsockname()

    print("Connected with " + str(ip) + ":" + str(port))

    try:
        Thread(target=client_thread, args=(connection, ip, port)).start()
    except:
        print("Thread did not start.")
        traceback.print_exc()

客户端线程

def client_thread(connection, ip, port, max_buffer_size = 5120):
    is_active = True

    while is_active:
        client_input = receive_input(connection, max_buffer_size)

        if "--QUIT--" in client_input:
            print("Client is requesting to quit")
            connection.close()
            print("Connection " + str(ip) + ":" + str(port) + " closed")
            is_active = False
        else:
            print("Processed result: {}".format(client_input))
            connection.sendall(client_input)

def receive_input(connection, max_buffer_size):
    client_input = connection.recv(max_buffer_size)
    client_input_size = sys.getsizeof(client_input)

    if client_input_size > max_buffer_size:
        print("The input size is greater than expected {}".format(client_input_size))

    decoded_input = client_input.decode("utf8").rstrip()  # decode and strip end of line
    result = process_input(decoded_input)

    return result

def process_input(input_str):
    print("Processing the input received from client")
    return "Hello " + str(input_str).upper()

客户

def main():
    soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = "192.168.8.241"
    port = 1024
    print("client_soc", soc)

    try:
        soc.connect((host, port))
    except:
        print("Connection error")
        sys.exit()

    print("Enter 'quit' to exit")
    message = input(" -> ")

    while message != 'quit':
        soc.sendall(message.encode("utf8"))
        while True:
            data = soc.recv(1024)
            print("Received response:" + str(data))
            message = input(" -> ")


    soc.send(b'--quit--')

0 个答案:

没有答案