python socket server

import json import requests import socket class Web: def __init__(self): self.HOST = '' self.PORT = 8888 self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.listen_socket.bind((self.HOST, self.PORT)) self.listen_socket.listen(1) def start(self): print 'Serving HTTP on port %s ...' % self.PORT while True: client_connection, client_address = self.listen_socket.accept() self.process_request(client_connection) http_response = "HTTP/1.1 200 OK" client_connection.sendall(http_response) client_connection.close() def process_request(self, connection): init_data = connection.recv(1024) lines = init_data.splitlines() method = lines[0].split(' ')[0] path = lines[0].split(' ')[1] protocol = lines[0].split(' ')[2] headers = {} for line in lines[1:]: if line != '': headers[line[0:line.index(':')]] = line[line.index(':')+1:].strip() content = lines[len(lines)-1] data_left = int(headers['Content-Length']) - len(content) if data_left > 0: content += connection.recv(data_left) print method, path, protocol print headers print content if __name__ == '__main__': web = Web() web.start()

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.