반응형
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 | #!/usr/bin/python 3.5.2 from socket import * import sys serverSocket = socket(AF_INET, SOCK_STREAM) serverPort = 12345 serverSocket.bind(('127.0.0.1',serverPort)) serverSocket.listen(1) while True: #Establish the connection print('Ready to serve...') connectionSocket, addr = serverSocket.accept() requestedParameter = {} try: message = connectionSocket.recv(1024).decode() # parsing request requestedParameter['method'] = message.split()[0] requestedParameter['filename'] = message.split()[1] requestedParameter['HTTP'] = message.split()[2] tmp = [] tmp = message.split('\r\n') i = 2 while True: if not tmp[i]: break requestedParameter[tmp[i].split(': ')[0]] = tmp[i].split(': ')[1] i += 1 #print(requestedParameter) if 'GET' == requestedParameter['method']: #response outputdata = "" f = open(requestedParameter['filename'][1:],'rt', encoding="UTF8") filedata = f.read() f.close() #Send HTTP header line into socket outputdata += requestedParameter['HTTP'] + " 200 OK\r\n" outputdata += "Date: Wed, 27 Sep 2018 16:30:31 GMT\r\n" outputdata += "Server: Apache/2.0.1\r\n" outputdata += "Accept-Ranges: bytes\r\n" outputdata += "Conetent-Length: " + str(len(filedata)) + "\r\n" outputdata += "Keep-Alive: timeout=10, max=100\r\n" outputdata += "Connection: Keep-Alive\r\n" outputdata += "Content-Type: text/html ; charset=ISO-8859-1\r\n" outputdata += "\r\n" outputdata += filedata #Send the content of the requested file to the client for i in range(0, len(outputdata)): connectionSocket.send(outputdata[i].encode()) connectionSocket.send("\r\n".encode()) connectionSocket.close() except IOError: #connectionSocket.send("IOError\r\n".encode()) outputdata += requestedParameter['HTTP'] + " 404 Not Found\r\n" outputdata += "Content-Type: text/html ; charset=ISO-8859-1\r\n" outputdata += "\r\n" f404 = open("404.html", 'rt', encoding="UTF8") outputdata += f404.read() for i in range(0, len(outputdata)): connectionSocket.send(outputdata[i].encode()) connectionSocket.send("\r\n".encode()) connectionSocket.close() serverSocket.close() sys.exit() #Terminate the program after sending the corresponding data | cs |
반응형
'Programming$ > Web Develop' 카테고리의 다른 글
[JavaScript] removeAttribute() (0) | 2019.05.07 |
---|---|
[JavaScript] practice 1 (0) | 2019.03.06 |
[.CSS] input cursor 없애기 (0) | 2019.02.26 |
[.CSS] z-index element 우선순위 (0) | 2019.02.26 |
[.CSS] 구글 폰트 적용하기 (1) | 2019.02.26 |