while True: print(‘waiting for connection...‘) tcpCliSock, addr = tcpSerSock.accept() print(‘...connected from: ‘, addr)
while True: data = tcpCliSock.recv(BUFSIZE) data = data.decode(‘utf8‘) if not data: break ss = ‘[%s] %s‘ %(ctime(), data) tcpCliSock.send(ss.encode(‘utf8‘)) print(ss) if data == ‘bye‘: quit = True break elif data == ‘shutdown‘: shutdown = True break print(‘Bye-bye: [%s: %d]‘ %(addr[0], addr[1])) tcpCliSock.close() if shutdown: break tcpSerSock.close() print(‘Server has been‘)
while True: data = input(‘>‘) if not data: continue print(‘input data: [%s]‘ %data) tcpCliSock.send(data.encode(‘utf8‘)) rdata = tcpCliSock.recv(BUFSIZE) if not rdata: break print(rdata.decode(‘utf8‘)) if data == ‘bye‘ or data == ‘shutdown‘: break tcpCliSock.close()
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request.recv(1024) cur_thread = threading.current_thread() response = "{}: {}".format(cur_thread.name, data) self.request.sendall(response)
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass
if __name__ == "__main__": # Port 0 means to select an arbitrary unused port HOST, PORT = "localhost", 0
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) ip, port = server.server_address
# Start a thread with the server -- that thread will then start one # more thread for each request server_thread = threading.Thread(target=server.serve_forever) # Exit the server thread when the main thread terminates server_thread.daemon = True server_thread.start() print "Server loop running in thread:", server_thread.name