这是一个简单的服务器。当您打开浏览器类型到服务器的地址时,它将响应状态代码和所请求的html的内容。但是当我添加这句“connectionSocket.send('HTTP / 1.1 200 OK')”时,没有任何回复。当我删除它时,html返回。另一个问题是,当我通过网络浏览器发送请求时,有两个连接发送到服务器,一个显示它想找到一个名为favicon.ico的文件,但当然这是一个IOError,因为没有这样的文件我的服务器的根目录。代码附后并感谢您的帮助。
#import socket module from socket import * serverSocket = socket(AF_INET,SOCK_STREAM) #prepare a server socket serverSocket.bind(('192.168.0.101', 8765)) serverSocket.listen(1) while True: #Establish the connection print 'Ready to serve...' connectionSocket,addr = serverSocket.accept() print 'connected from',addr try: message = connectionSocket.recv(1024) filename = message.split()[1] print filename f = open(filename[1:]) outputdata = f.read() #Send one HTTP header line into socket #connectionSocket.send('HTTP/1.1 200 OK') #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: print 'IOError' #Send response message for file not found connectionSocket.send('file not found') #Close Client socket connectionSocket.close() serverSocket.close()
答案 0 :(得分:5)
您需要将新行(\r\n\r\n
)添加到HTTP标头的末尾:
connectionSocket.send('HTTP/1.1 200 OK\r\n\r\n')
此外,您可能应该使用更高级别的库来编写HTTP服务器...
答案 1 :(得分:0)
您是否尝试将返回值从string
转换为bytes
替换它:
connectionSocket.send('HTTP/1.1 200 OK\r\n\r\n')
有了这个
connectionSocket.send(bytes('HTTP/1.1 200 OK\r\n\r\n','UTF-8'))