简体   繁体   English

为什么使用Python套接字的HTTP响应失败?

[英]Why does my HTTP response using Python Sockets fail?

Code: 码:

from socket import *
sP = 14000
servSock = socket(AF_INET,SOCK_STREAM)
servSock.bind(('',sP))
servSock.listen(1)

while 1:
  connSock, addr = servSock.accept()
  connSock.send('HTTP/1.0 200 OK\nContent-Type:text/html\nConnection:close\n<html>...</html>')
connSock.close()

When I go to the browser and type in localhost:14000, I get an error 101- ERR_CONNECTION_RESET The connection was reset? 当我进入浏览器并输入localhost:14000时,出现错误101- ERR_CONNECTION_RESET连接被重置了? Not sure why! 不知道为什么! What am I doing wrong 我究竟做错了什么

Several bugs, some more severe than others ... as @IanWetherbee already noted, you need an empty line before the body. 几个错误,有些比其他错误更严重......正如@IanWetherbee已经注意到的那样,你需要在身体前面留空线。 You also should send \\r\\n not just \\n. 你也应该发送\\ r \\ n而不仅仅是\\ n。 You should use sendall to avoid short sends. 您应该使用sendall来避免短发。 Last, you need to close the connection once you're done sending. 最后,您需要在完成发送后关闭连接。

Here's a slightly modified version of the above: 这是上面的略微修改版本:

from socket import *
sP = 14000
servSock = socket(AF_INET,SOCK_STREAM)
servSock.bind(('',sP))
servSock.listen(1)

while 1:
  connSock, addr = servSock.accept()
  connSock.sendall('HTTP/1.0 200 OK\r\nContent-Type:text/html\r\nConnection:close\r\n\r\n<html><head>foo</head></html>\r\n')
  connSock.close()

Running your code, I have similar errors and am unsure on their origins too. 运行你的代码,我有类似的错误,也不确定它们的起源。 However, rather than rolling your own HTTP server, have you considered a built in one? 但是,您是否考虑过内置的HTTP服务器,而不是滚动自己的HTTP服务器? Check out the sample below. 看看下面的示例。 This can also support POST as well (have to add the do_POST method). 这也可以支持POST(必须添加do_POST方法)。

Simple HTTP Server 简单的HTTP服务器

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class customHTTPServer(BaseHTTPRequestHandler):
        def do_GET(self):
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                self.wfile.write('<HTML><body>Hello World!</body></HTML>')
                return 

def main():
        try:
                server = HTTPServer(('',14000),customHTTPServer)
                print 'server started at port 14000'
                server.serve_forever()
        except KeyboardInterrupt:
                server.socket.close() 

if __name__=='__main__':
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM