当前正在执行一项任务,我们在python中编写套接字,从而在webserver.py代码执行时创建一个Web服务器。然后,代码在访问文件时应该显示HTTP标头和其他信息(test.html)。现在我的代码工作(或者我想这样做),并且我创建了一个test.html文件,接下来的问题是我应该将test.html文件放在与Web服务器相同的目录中,在我的本地机器上?我将test.html放在python根目录下的webserver.py所在的文件夹中,然后前往127.0.0.1:1336/test.html来测试我的代码,但它不起作用,我的机器上的确切位置是web服务器我应该放置test.html的目录?是否必须使用wamp/xamp并将test.html放在那里?Web服务器和套接字编程
N.B 1336是我在代码中指定的端口,用于连接。
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverPort = 1336
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serverSocket.bind(('', serverPort)) #set up socket connection
serverSocket.listen(1) #tells the server to try a maximum of one connect request before ending connection
while True:
#Establish the connection
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()
print 'connected to port',serverPort
try:
message = connectionSocket.recv(1024) #Makes it so that you can recieve message from client
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.open(filename[1:])
#Send one HTTP header line into socket2
#Fill in start
connectionSocket.send('HTTP/1.0 200 OK\r\n')
#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
print '404 Error : File Not Found.'
#Close client socket
connectionSocket.close()
serverSocket.close()
感谢您的建议,添加了代码。试着让它工作 – 2014-10-03 01:22:26