1

I'm working on a very simple server. This server should be able to do some predefined commands requested by clients.

I would like to store information about connected clients separately. For example, I want server to add a number of the particular clients requests.

Here is an example:

SERVER
CLIENT1 
CLIENT2

CLIENT1> print 'stuff'
SERVER>> REQUESTS: 1 OUTPUT: stuff
CLIENT2> print 'simple sentence'
SERVER>> REQUESTS: 1 OUTPUT: simple sentence
CLIENT> print 'hilarious'
SERVER>> REQUESTS: 2 OUTPUT: hilarious

My code is simple:

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    daemon_threads = True

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        data = self.request.recv(1024)
        command = data.split(' ')[0]
        arguments = data.split(' ')[1:]
        cur_thread = threading.current_thread()

        output = do_command(command,arguments)
        response = "{}: {}".format(cur_thread.name, output)
        self.request.sendall(response)


if __name__ == "__main__":
    commands.register_commands()
    HOST, PORT = _host, int(_port)

    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
    ip, port = server.server_address

    # start server
    print "Running on: %s:%s" % (HOST, PORT)
    server.serve_forever()

So the thing I want to know is how could I store information about each client. I was considering to create a class Client and make an object after each connection but I don't know where should I create this objects.

Milano
  • 18,048
  • 37
  • 153
  • 353

1 Answers1

1

You could use the client_address property of the handler to identify clients, and track requests in a global dict:

from collections import defaultdict

client_requests = defaultdict(int)

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        ...
        client_requests[self.client_address[0]] += 1
        response = "{} ({}): {}".format(cur_thread.name, client_requests[self.client_address[0]], output)

Note that since you're using a threaded server, you'll probably need to add some locking code to protect the writes to client_requests, but that's an exercise left to the reader.

glibdud
  • 7,550
  • 4
  • 27
  • 37
  • Thank you, self.client_address was exactly what I was looking for. I'm testing it on my local computer, so client_address[0] is localhost for all clients but client_address should be unique. – Milano Jan 28 '16 at 23:30
  • @Milano Yes, you can use that as long as the clients stay connected between requests. If they reconnect, they'll probably get a different port. – glibdud Jan 28 '16 at 23:34