为什么客户端会收到错误的信息——sockets Python

时间:2021-03-27 15:23:35

标签: python multithreading sockets network-programming client-server

我正在尝试用 Python 编写一个小型客户端-服务器应用程序。服务器必须生成一个随机数并将其发送给客户端。客户端检查它收到的数字是否是素数。在这种情况下,它将向服务器发送消息“是”。如果数字不是质数,它将向服务器发送“NO”消息。然后服务器检查回复,如果是“是”/“否”,它将向客户端发送消息“正确”/“错误”,客户端将显示它。该应用程序适用于一个客户端,但是当多个客户端同时访问该应用程序时,我会收到如下错误:“int() 的无效文字以 10 为基数:'错误'”,有时我会收到“一个现有的连接是被远程主机强行关闭”。你能告诉我我做错了什么吗?

server.py:

import socket
import random
import threading

class ClientHandler(threading.Thread):
    def __init__(self, client_sock, client_addr):
        self.client_sock = client_sock
        self.client_addr = client_addr
        super(ClientHandler, self).__init__()

    def run(self):
        n = random.randint(0, 9)
        trimite = str(n)
        self.client_sock.send(bytes(trimite, "utf-8"))

        received = None
        while received == None:
            received = client_sock.recv(100)

        received = received.decode("utf-8")

        if received == "YES":
             client_sock.send(b"Correct")
        else:
             client_sock.send(b"Wrong")

        self.client_sock.close()

if __name__ == '__main__':
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(("0.0.0.0", 9999))
    sock.listen(10)

    while True:
        client_sock, client_addr = sock.accept()
        print(f"Connected {client_addr[0]} : {client_addr[1]}")
        worker_thread = ClientHandler(client_sock, client_addr)
        worker_thread.start()

client.py:

import socket
import threading


def check_prime(n):

    n = int(n)

    if n == 1 or n == 0:
        return False
    if n == 2:
        return  True
    for i in range(2, n // 2):
        if n % i == 0:
            return False
    return True

class RunMultiple(threading.Thread):
    def __init__(self, sock):
        self.sock = sock
        super(RunMultiple, self).__init__()

    def run(self):

        recieved = self.sock.recv(100)
        if check_prime(recieved.decode("utf-8")) == True:
            self.sock.send(b"YES")
        else:
            self.sock.send(b"NO")

        second_recieved = self.sock.recv(100)
        print(second_recieved.decode("utf 8"))

if __name__ == "__main__":
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    sock.connect(("127.0.0.1", 9999))
    i = 0
    while i != 3:
        worker_thread = RunMultiple(sock)
        worker_thread.start()
        i += 1

1 个答案:

答案 0 :(得分:0)

为每个客户端打开一个新连接:

if __name__ == "__main__":
    for i in range(3):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.connect(("127.0.0.1", 9999))
        worker_thread = RunMultiple(sock)
        worker_thread.start()

并确保在服务器中使用 self.client_sock 而不是 client_sock。如果没有它,它会引用代码的 if __name__ 部分中定义的全局变量,这是最后打开的套接字。

        received = None
        while received == None:
            received = self.client_sock.recv(100) # was missing self here

        received = received.decode("utf-8")

        if received == "YES":
             self.client_sock.send(b"Correct") # and here
        else:
             self.client_sock.send(b"Wrong")   # and here

        self.client_sock.close()