【计算机网络】WebServer实现并从本机读取多个文件

来源:互联网 发布:幼儿园食谱软件下载 编辑:程序博客网 时间:2024/06/07 04:44

这是《计算机网络(自顶向下方法)》第二章练习题的实现
有两个问题还有待解决:

  • 什么是多线程
  • 如何发送HTTP HEADER及其意义

client.py

__author__ = 'yang'import socketserverName = 'hostname'serverPort = 12000clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)clientSocket.connect((serverName, serverPort))filenames = raw_input('Input filenames, split by comma:\n')#print filenamesclientSocket.send(filenames)fileContent = clientSocket.recv(2048)print fileContent

webserver.py

__author__ = 'yang'import socketserverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)serverPort = 12000serverSocket.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()
1 0
原创粉丝点击