#!/usr/bin/python import socket my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #the first parameter indicates that #the socket is an internet socket #and the second parameter indicates #that it uses TCP HOST = "127.0.0.1" # Loopback interface PORT = 1060 # Sufficiently obscure port # method written by Brandon Rhodes/John Goerzen in Foundations of Python Network Programming def recv_all(sock, length): data = '' while len(data) < length: more = sock.recv(length - len(data)) if not more: raise EOFError('socket closed') data += more return data my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # makes it so we can reuse the port # number immediately after this # program is done my_socket.bind((HOST, PORT)) while True: my_socket.listen(1) # this parameter keeps track of how many connections to back up print "Next client" clients_socket, clients_socket_name = my_socket.accept() length = int(recv_all(clients_socket, 3)) print length msg = recv_all(clients_socket, length) print(msg) clients_socket.sendall("Received!") clients_socket.close()