所以,我试图在python上创建一个简单的服务器,并尝试通过它访问同一目录中的html文件,但作为输出我继续准备服务... output
编辑:将HTML文件(例如,HelloWorld.html)放在服务器所在的目录中。运行服务器程序。确定运行服务器的主机的IP地址(例如,128.238.251.26)。从其他主机,打开浏览器并提供相应的URL。例如:http://128.238.251.26:6789/HelloWorld.html'HelloWorld.html'是您放在服务器目录中的文件的名称。还要注意冒号后使用端口号。您需要将此端口号替换为您在服务器代码中使用的任何端口。在上面的示例中,我们使用了端口号6789.然后,浏览器应显示HelloWorld.html的内容。如果省略“:6789”,浏览器将采用端口80,只有当服务器正在侦听端口80时,才会从服务器获取网页。然后尝试获取服务器上不存在的文件。您应该收到“404 Not Found”消息。
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverSocket.bind(('', 12006))
serverSocket.listen(1)
while True:
print 'Ready to serve...'
#Establish the connection
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
f.close()
#Send one HTTP header line into socket
connectionSocket.send('HTTP/1.0 200 OK\r\n\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
connectionSocket.send('404 Not Found')
#Close client socket
connectionSocket.close()
serverSocket.close()
您的输出是标准输出,通过qazxsw poi函数使用。你应该向你的服务器发出请求,你会得到正确的输出
如果你的本地机器上的服务器,你应该使用print
地址;如果没有,你应该使用你的服务器IP。您还应该指定一个端口。在你的情况下localhost
。以12006
为例
此外,localhost:12006
方法需要一个类似字节的对象。不是字符串
如果它只是一个字符串socket.send
,你应该在第一个引号前添加一个literal字符
例:
b
如果它是connectionSocket.send(b'HTTP/1.0 200 OK\r\n\r\n')
对象,您应该对其进行编码:
string
看看connectionSocket.send(outputdata[i].encode())