您的位置:首页 > 理论基础 > 计算机网络

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

2016-01-09 16:27 369 查看
这是《计算机网络(自顶向下方法)》第二章练习题的实现

有两个问题还有待解决:

什么是多线程

如何发送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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: