Created
September 27, 2019 10:43
-
-
Save fanny/5e3f8081719d305af2890b656f0bff95 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import socket | |
| import sys | |
| server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
| server_socket.bind(('', 3000)) | |
| server_socket.listen(9000) | |
| print('The server is connected on the port {}'.format(3000)) | |
| while True: | |
| connection, addr = server_socket.accept() | |
| message = connection.recv(1024).decode('utf-8') | |
| message_parts = message.split(' ') | |
| header = None | |
| response = None | |
| try: | |
| method = message_parts[0] | |
| file_path = message_parts[1] | |
| http_version = message_parts[2].split('\r\n')[0] | |
| if file_path == '/': | |
| file_path += 'index.html' | |
| file_name = file_path.split('/')[-1] | |
| with open('.' + file_path, 'rb') as file: | |
| response = file.read() | |
| header = '{} 200 OK\r\n'.format(http_version) | |
| mimetype = 'Content-Type: ' | |
| ext = file_path.split('.')[-1] | |
| if ext == 'txt': | |
| mimetype += 'text/plain' | |
| elif ext == 'html': | |
| mimetype += 'text/html' | |
| else: | |
| mimetype = None | |
| mimetype += '\r\n' | |
| if mimetype: | |
| header += mimetype | |
| else: | |
| header += 'Content-Disposition: form-data; name="files"; filename="{}"\r\n'.format(file_name) | |
| except: | |
| header = '{} 404 Not Found\n\n'.format(http_version) | |
| response = '<html><body><h1>Error 404</h1></body></html>' | |
| output = header.encode('utf-8') | |
| output += '\r\n'.encode('utf-8') | |
| output += response | |
| output += '\r\n'.encode('utf-8') | |
| connection.send(output) | |
| connection.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment