0
我創建了一個接收請求的代理服務器,在其緩存中搜索請求的文件。如果可用,則返回緩存的文件。如果文件不可用,那麼它會詢問實際的服務器,獲取它,將其存儲在緩存中並將文件返回給客戶端。針對網絡服務器的Python套接字編程
以下是代碼:
from socket import *
import sys
if len(sys.argv) <= 1:
print 'Usage : "python ProxyServer.py server_ip"\n[server_ip : It is the IP Address Of Proxy Server'
sys.exit(2)
# Create a server socket, bind it to a port and start listening
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind((sys.argv[1], 8888))
tcpSerSock.listen(100)
while 1:
# Strat receiving data from the client
print 'Ready to serve...'
tcpCliSock, addr = tcpSerSock.accept()
print 'Received a connection from:', addr
message = tcpCliSock.recv(1024)
print message
# Extract the filename from the given message
print message.split()[1]
filename = message.split()[1].partition("/")[2]
print filename
fileExist = "false"
filetouse = "/" + filename
print filetouse
try:
# Check wether the file exist in the cache
f = open(filetouse[1:], "r")
outputdata = f.readlines()
fileExist = "true"
# ProxyServer finds a cache hit and generates a response message
tcpCliSock.send("HTTP/1.0 200 OK\r\n")
tcpCliSock.send("Content-Type:text/html\r\n")
for i in range(0, len(outputdata)):
tcpCliSock.send(outputdata[i])
print 'Read from cache'
# Error handling for file not found in cache
except IOError:
if fileExist == "false":
# Create a socket on the proxyserver
c = socket(AF_INET, SOCK_STREAM)
hostn = filename.replace("www.","",1)
print hostn
try:
# Connect to the socket to port 80
c.connect((hostn, 80))
# Create a temporary file on this socket and ask port 80 for the file requested by the client
fileobj = c.makefile('r', 0)
fileobj.write("GET "+"http://" + filename + " HTTP/1.0\n\n")
# Read the response into buffer
buff = fileobj.readlines()
# Create a new file in the cache for the requested file. Also send the response in the buffer to client socket and the corresponding file in the cache
tmpFile = open("./" + filename,"wb")
for line in buff:
tmpFile.write(line);
tcpCliSock.send(line);
except:
print "Illegal request"
else:
# HTTP response message for file not found
tcpCliSock.send("HTTP/1.0 404 sendErrorErrorError\r\n")
tcpCliSock.send("Content-Type:text/html\r\n")
tcpCliSock.send("\r\n")
# Close the client and the server sockets
tcpCliSock.close()
tcpSerSock.close()
但對於每一個文件我請求我只得到一個「非法請求」消息打印。似乎有一個問題,代理服務器實際上無法檢索客戶端請求的文件。有人可以告訴我在哪裏可以改進代碼。 這是我第一次用Python編碼,所以請提及任何小錯誤。
我投票結束這個問題作爲題外話題,因爲它是關於調試一段特定的代碼。我相信這將是在http://codereview.stackexchange.com/ – 2015-04-05 03:35:18
根據主題,根據代碼審查幫助中心,該網站是「關於特定的**工作**代碼塊的反饋」(強調他們的)並且明確地不是用於「解決問題,調試或理解代碼片段」。我相信StackOverflow是這個網站的正確站點(因爲它似乎是一個合法的問題,而不是「給我這個codez」),假設OP主要對解決這個「非法請求」錯誤感興趣。 – Ixrec 2015-04-05 08:10:27