Marius Marius - 1 month ago 15
Python Question

Running multiple sockets at the same time in python

I am trying to listen and send data to several sockets at the same time. When I run the program I get en error saying:

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 704, in __init__
if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:


OSError: [Errno 9] Bad file descriptor

The first socket starts up correctly, but once I try to start a new one I get the error.

class bot:
def __init__(self, host, port):
self.host = host
self.port = port

sock = socket.socket()
s = None

def connect_to_server(self):
self.s = ssl.wrap_socket(self.sock)
self.s.connect((self.host, self.port))


Above is the class and then I'm running several instances.

def run_bots(bots):
for bot in bots:
try:
threading.Thread(target=bot.connect_to_server()).start()
except:
print(bot.host)
print("Error: unable to start thread")
bots = []
b = bot('hostname.com', 1234)
b1 = bot('hostname1.com', 1234)
bots.append(b)
bots.append(b1)
run_bots(bots)


I don't know what to do. Anyone have an idea of what could be the problem?

Answer

You are using the same socket. Create one for each bot:

class bot:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.s = None

    def connect_to_server(self):
        sock = socket.socket()
        self.s = ssl.wrap_socket(sock)
        self.s.connect((self.host, self.port))