这是《计算机网络(自顶向下方法)》第二章练习题的实现
有两个问题还有待解决:
- 什么是多线程
- 如何发送HTTP HEADER及其意义
client.py
__author__ = 'yang'
import socket
serverName = 'hostname'
serverPort = 12000
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
filenames = raw_input('Input filenames, split by comma:\n')
#print filenames
clientSocket.send(filenames)
fileContent = clientSocket.recv(2048)
print fileContent
webserver.py
__author__ = 'yang'
import socket
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverPort = 12000
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print 'Ready to serve\n'
while 1:
print 'start'
connectionSocket, addr = serverSocket.accept()
message = connectionSocket.recv(2048)
print message
filename = message.split(',')
outputdata = []
for i in range(0,len(filename)):
with open(filename[i]) as file:
outputdata.append(file.read())
#send one HTTP header line into socket,此处还未完成
#print outputdata,len(outputdata)
#send the content of the requested file to the client
fileContent = ''
for i in range(0,len(outputdata)):
fileContent = fileContent + outputdata[i]
print fileContent
connectionSocket.send(fileContent)
connectionSocket.close()
#send response message for file not found
#connectionSocket.send("file not found")
serverSocket.close()
还有一个问题,即客户端收到服务器的一个段后应何时关闭套接字。
我个人认为这应该是又HTTP协议中决定的,不知道代码中是否需要
clientSocket.close()