#!/usr/bin/python import socket # Import socket module from threading import Thread def on_new_client(clientsocket, addr): try: while True: msg = clientsocket.recv(1024) if not msg: break print(addr, ' >> ', str(msg, 'utf-8')) # echo the message back clientsocket.send(msg) finally: print('Connection to client', addr, 'closed') clientsocket.close() s = socket.socket() # Create a socket object s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) port = 50000 # Reserve a port for your service. s.bind(('127.0.0.1', port)) # Bind to the port s.listen(5) # Now wait for client connection. print('Server started!') try: while True: c, addr = s.accept() # Establish connection with client. print('Got connection from', addr) Thread(target=on_new_client, args=(c,addr)).start() finally: s.close()