Francesco
Francesco

Reputation: 531

Client-side Socket on Python, how to contact multiple server?

I have a client that needs to contact some servers. So the sockets on the client will connect to a specific server port and host but how can I switch from one server to an other? So my easy Client looks like:

import socket
import sys

class Client:

    def __init__(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if self.s is None:
            print('could not open socket')
            sys.exit(1)
        self.servers = { 1998: True, 1999: True }
        self.current_file = None
        self.host = '127.0.0.1'
        if len(sys.argv) > 1:
            self.host = sys.argv[1]

    def IterateServer(self):
        keys = self.servers.keys()
        for key in keys:
            try:
                self.s.connect((self.host, key))
            except socket.error as msg:
                self.servers[key] = False
                continue
            print('Connect' + str(key))

My question is about IterateServer(self)

When I set the socket connection, it works for the first server (port 1998) but not for the second. I think that when I connect a socket to an other I cannot re-connect it, am I right?

Upvotes: 1

Views: 150

Answers (1)

turbulencetoo
turbulencetoo

Reputation: 3691

My strategy would be to have a dictionary that maps servers to the socket that is open with that server.

I'd initialize with None, indicating that no socket is open there.

self.servers = { 1998: None, 1999: None }

Then, in the loop:

def IterateServer(self):
    for key in self.servers:
        try:
            tmp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            tmp_sock.connect((self.host, key))
        except socket.error as msg:
            # Didn't work! Entry in dict stays as None
            continue
        # Did work! Update the dict with our open socket.
        self.servers[key] = tmp_sock
        print('Connect' + str(key))

Now you could write to all servers with something like

def write_to_all_servers(self, string_to_write):
    for key, sock in self.servers.items():
        if sock is not None:
            sock.write(string_to_write)

Upvotes: 1

Related Questions