如何使用线程在Python中运行简单的服务器和客户端

vyswwuz2  于 2023-05-02  发布在  Python
关注(0)|答案(1)|浏览(130)

我有两个相同的脚本,分别在每个脚本上运行客户端和服务器,
脚本1:

import socket
import threading
import time

# this clients socket is known as conn in server
# ip of the server you want to connect to

HOST = "196.248.183.205"  # socket.gethostbyname(socket.gethostname())
PORT = 49000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))

def boot_server():
    while True:
        server.listen()
        print("starting server...")
        print(f"server binding {HOST, PORT}")
        thread = threading.Thread(target=start_client())
        time.sleep(2)
        thread.start()
        conn, addr = server.accept()
        print(f"{addr} is connected")
        message = conn.recv(1024).decode("utf-8")
        print(f"message has been received {message}")

def start_client():
    print("starting client...")
    while True:
        clientsocket.connect((HOST, 44355))  # conn to other server ip and port
        clientsocket.recv(1024).decode()

boot_server()
time.sleep(1)

脚本二:

import socket
import threading
import time

# this clients socket is known as conn in server
# ip of the server you want to connect to

HOST = "196.248.183.205"  # socket.gethostbyname(socket.gethostname())
PORT = 44355
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))

def boot_server():
    while True:
        server.listen()
        print("starting server...")
        print(f"server binding {HOST, PORT}")
        thread = threading.Thread(target=start_client())
        time.sleep(2)
        thread.start()
        conn, addr = server.accept()
        print(f"{addr} is connected")
        conn.recv(f"connection is successful")

def start_client():
    print("starting client...")
    while True:
        clientsocket.connect((HOST, 49000))  # conn to other server ip and port
        clientsocket.recv(1024).decode()

boot_server()
time.sleep(1)
clientsocket.send("verificationcode".encode("utf-8"))

当运行脚本时,任何一个脚本都可以启动连接,但是如果连接可以保持打开,我更喜欢它,如果我不尽快运行另一个脚本,两个脚本都会失败,返回的消息是:请注意,当首先运行此脚本时,clientsocket中的端口将更改为49000 clientsocket.connect((HOST, 44355)) # conn to other server ip and port ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
问题是,即使脚本1上的服务器和客户端都连接到脚本2,它们也不会从脚本2向脚本1交换数据。脚本2:clientsocket.send("verificationcode".encode("utf-8"))
我希望脚本1中的服务器接收来自脚本2的数据,但进程没有经过print("starting client..."),我不确定这是否是由于函数boot_server()中创建的循环造成的

inkz8wg9

inkz8wg91#

创建线程时调用函数。您应该只将函数传递给Thread类。它会在必要时调用它自己。

thread = threading.Thread(target=start_client())

把上面的代码改成这样:

thread = threading.Thread(target=start_client)

相关问题