How to only allow one client to connect to my TCPSocketServer?

1.5k views Asked by At

I have overridden the handle function. Right now, every time a client connects, it will keep the socket open to echo what the client sent in all caps. The server should not allow more than one connection, thus only one socket is kept open. How would this be done?

Server -

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):


    def handle(self):
        while 1:
            self.data = self.request.recv(1024).strip()
            print self.data
            # echo back data in all caps
            self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
    server = SocketServer.ThreadingTCPServer((HOST, PORT), MyTCPHandler)

    server.serve_forever()

The client needs to do work with the server for some amount of time (10 seconds in this example). The server should not accept connections from any other client during this time.

Client -

import socket
import sys
import time

HOST, PORT = "localhost", 9999
data = 1
future = time.time() + 10  # work for 10 seconds

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    # Connect to server and send data
    sock.connect((HOST, PORT))
except socket.error:
    sys.exit()

else:
    while time.time() < future:
        sock.sendall(data + "\n")
        received = sock.recv(1024)
        print received
        data += 1

finally:
    sock.close()
1

There are 1 answers

7
PasteBT On BEST ANSWER

Your handle will never quit, and because you did not use any multithreading/multiprocessing, it will serve one connection forever. So first you should have some way to quit. Such as a message "quit" from the client side. Like this:

def handle(self):
    while 1:
        self.data = self.request.recv(1024).strip()
        print self.data
        if self.data == 'quit':
            break
        # echo back data in all caps
        self.request.sendall(self.data.upper())