1. 程式人生 > >計算機網路(1)——簡易的Web Server

計算機網路(1)——簡易的Web Server

#file name:PA01_1.py
#writer:Zhang_Jingtun(Ordinary_Crazy)
#initial date:20180310
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
#Fill in start
HOST = '10.162.88.123'
PORT = 8081
serverSocket.bind((HOST,PORT)) 	#address and port
serverSocket.listen(1)			#begin to listen
#Fill in end
while True:
	#Establish the connection
	print ('Ready to serve...')
	connectionSocket, clientaddr = serverSocket.accept() #receive TCP connection and return new socket and IP address
	print ('Connected by',clientaddr)
	try:
		message = connectionSocket.recv(1024)
		filename = message.split()[1]
		f = open(filename[1:])
		outputdata = f.read()
		#Send one HTTP header line into socket
		connectionSocket.send('HTTP/1.1 200 OK\r\n\r\n'.encode())
		#Send the content of the requested file to the client
		for i in range(0, len(outputdata)):
			connectionSocket.send(outputdata[i].encode())
		connectionSocket.close()
	except IOError:
		#Send response message for file not found
		connectionSocket.send('404 Not Found'.encode())
		#Close client socket
		connectionSocket.close()
serverSocket.close()