如何让多个客户端连接到 python 中的同一个源?

How do I get multiple clients to connect to the same source in python?

我在 python 中做了一个 class,里面有一个插座。当我尝试 运行 相同 class 的多个实例时,出现此错误:

error: [Errno 10056] A connect request was made on an already connected socket

我可以看到错误在说什么,但我认为 classes 在 运行 时彼此独立。所以不会干扰。

这是我使用的代码:

class Bot():

    HOST = "localhost"
    PORT = 6667
    s = socket.socket()

    def Connect(self):

        self.s.connect((self.HOST, self.PORT))

然后当我创建机器人时:

bots = []

def Setup_Bot():

    global bots

    _bot = Bot()

    _bot.Connect()

    bots.append(_bot)

if __name__ == "__main__":

    for i in range(5):

        Setup_Bot()

        sleep(1)

    print "Done Setting Up"

我怎样才能让它工作?

将套接字 s 设为实例变量,而不是将其设置在 class 上。您的所有 Bot 实例现在共享相同的 class 属性,因此共享相同的套接字。

class Bot():
    HOST = "localhost"
    PORT = 6667

    def __init__(self):
        self.s = socket.socket()

    def Connect(self):
        self.s.connect((self.HOST, self.PORT))