1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| import socket import threading import os
currentPath = os.getcwd().replace('\\','/')
def handle_conn(sock, address): print("deal with connection ....") t = threading.Thread(target=process_conn, args=(sock, address)) t.start()
def process_conn(sock, address): print(threading.current_thread())
while True: recv_data = sock.recv(1024) if recv_data: request=recv_data.decode() print(request)
headers = request.split('\n') filename = headers[0].split()[1]
headers = "HTTP/1.1 200 OK\n" + "Content-Type: text/html\n\n" if filename == '/': filename = '/index.html' elif filename.endswith(".jpg") : headers = "HTTP/1.1 200 OK\n" + "Content-Type: image/jpeg\n\n" elif filename.endswith(".txt") : headers = "HTTP/1.1 200 OK\n" + "Content-Type: text/plain\n\n" try: fin = open(currentPath+filename, "rb") content = fin.read() fin.close() response=headers.encode()+content
except FileNotFoundError: response = 'HTTP/1.0 404 NOT FOUND\n\nFile Not Found'.encode() except PermissionError: response = 'HTTP/1.0 403 FORBIDDEN\n\nNo Access Permission'.encode() sock.send(response) else: break print("close socket..") sock.close()
def main(): tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_server_socket.bind(("127.0.0.1", 8888)) tcp_server_socket.listen(5) while True: print(threading.current_thread()) print("waitting ........") new_client_socket, client_addr = tcp_server_socket.accept() handle_conn(new_client_socket, client_addr)
if __name__ == '__main__': main()
|