-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProjectA-Quang-14415297.py
53 lines (42 loc) · 1.52 KB
/
ProjectA-Quang-14415297.py
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
# import socket module
from socket import *
import sys # Terminate prog.
import threading # multithreading
# Prepare a sever socket
serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = 6789
serverSocket.bind(("192.168.0.2", serverPort))
def start():
serverSocket.listen()
print('Ready to serve...')
while True:
# Establish the connection
conn, addr = serverSocket.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.active_count() - 1}")
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
try:
message = conn.recv(1024).decode()
filename = message.split()[1]
f = open(filename[1:], 'r')
outputdata = f.read()
# Send one HTTP header line into socket
conn.send("HTTP/1.1 200 OK\r\n\r\n".encode())
conn.send("\r\n".encode())
# Send the content of the requested file to the client
for i in range(0, len(outputdata)):
conn.send(outputdata[i].encode())
conn.send("\r\n".encode())
conn.close()
except IOError:
# Send response message for file not found
conn.send("HTTP/1.1 404 Not Found\r\n\r\n".encode())
conn.send("<html><title>404 Not Found</title><body><h1>404 Not Found</h1></body></html>\r\n".encode())
# Close client socket
conn.close()
print("[STARTING] server is starting...")
start()
serverSocket.close()
sys.exit() # Terminate the program