これは単純なサーバーです。ブラウザでサーバーのアドレスを入力すると、リクエストされた html のステータス コードとコンテンツが返されます。
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverSocket.bind((socket.gethostname(), 4501))#Fill in start
serverSocket.listen(5)#Fill in end
while True:
#Establish the connection
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()#Accepts a TCP client connection, waiting until connection arrives
print 'Required connection', addr
try:
message = connectionSocket.recv(32)#Fill in start #Fill in end
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()#Fill in start #Fill in end
#Send one HTTP header line into socket
connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n')#Fill in start
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
#Send response message for file not found
connectionSocket.send('404 Not Found')#Fill in start
#Fill in end
#Close client socket
connectionSocket.close()#Fill in start
serverSocket.close()#Fill in end