from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR, SHUT_WR import sys # Create a server socket, bind it to a port and start listening tcpSerSock = socket(AF_INET, SOCK_STREAM) tcpSerPort=12002 # Assign IP address and port number to socket tcpSerSock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) tcpSerSock.bind(('', tcpSerPort)) tcpSerSock.listen(1) print ("listening on port %s" % tcpSerPort) while 1: # Start receiving data from the client print ('Ready to serve...') tcpCliSock, addr = tcpSerSock.accept() print ("Connection from %s port %s" % addr) # Receive the GET request from the client and echo it back buffer = '' message = "" more = True #this is a simplified way to read the file that will not always #work on a slow connection. It is better to parse the data, look #for the request type, find the end of the headers, check for #content-length bytes after the headers. headers = {} while more: buffer = buffer + tcpCliSock.recv(2048).decode() (all_headers, sep, post_data) = buffer.partition("\r\n\r\n") if sep != "": #found end of headers more = False lines = all_headers.split("\r\n") for line in lines: [key, sep, value] = line.partition(":") headers[key.upper()] = value print ("(header)", key.upper(), value) if "CONTENT-LENGTH" in headers: content_length = int(headers["CONTENT-LENGTH"]) while len(post_data) < content_length: post_data = post_data + tcpCliSock.recv(2048).decode() print ("POST DATA ", post_data) out='''\ HTTP/1.1 200 OK Content-type:text/plain Content-length: {0} {1}'''.format(len(buffer), buffer) tcpCliSock.send(out.encode()) # Close the client and the server sockets tcpCliSock.shutdown(SHUT_WR) tcpSerSock.close()