Search code examples
pythonsocketsclients

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


I made a class in python that has a socket in it. When I try to run multiple instances of the same class I get this error:

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

I can see what the error is saying, but I though the classes were independent of each other when they run. So it wouldn't interfere.

Here's the code I'm using:

class Bot():

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

    def Connect(self):

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

Then when I create the bots:

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"

How would I be able to get this to work?


Solution

  • Make the socket s an instance variable instead of setting it on the class. All your Bot instances now share the same class attributes and thus, the same socket.

    class Bot():
        HOST = "localhost"
        PORT = 6667
    
        def __init__(self):
            self.s = socket.socket()
    
        def Connect(self):
            self.s.connect((self.HOST, self.PORT))