社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

404在Python3中使用套接字库时未找到错误

user14918018 • 2 年前 • 106 次点击  

我试图在Python 3.8中运行以下示例代码:

import socket
mysock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com',80))

# since I need to send bytes and not a str. I add a 'b' literal also tried with encode()
mysock.send(b'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
    data = mysock.recv(512)
    if (len(data)) < 1:
        break
    print(data)
mysock.close()

但这是抛出404未找到错误

b'HTTP/1.1 404 Not Found\r\nServer: nginx\r\nDate: Tue, 02 Nov 2021 04:38:35 GMT\r\nContent-Type: text/html\r\nContent-Length: 146\r\nConnection: close\r\n\r\n<html>\r\n<head><title>404 Not Found</title></head>\r\n<body>\r\n<center><h1>404 Not Found</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n' 

和我用urllib试过的一样,它很好用

import urllib.request
output= urllib.request.urlopen('http://www.py4inf.com/code/romeo.txt')
for line in output:
    print(line.strip())

有人知道怎么解决这个问题吗?帮我找出我在第一个代码块中出错的地方。。 提前谢谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130633
 
106 次点击  
文章 [ 1 ]  |  最新文章 2 年前
Steffen Ullrich
Reply   •   1 楼
Steffen Ullrich    2 年前
mysock.send(b'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')

这不是有效的HTTP请求,原因如下:

  • 它应该包含绝对路径,而不是绝对URL
  • 它应该包含一个主机头。尽管这不是HTTP/1.0(但对于HTTP/1.1)的严格要求,但通常情况下都是这样
  • 行尾必须是 \r\n \n

以下工作:

mysock.send(b'GET /code/romeo.txt HTTP/1.0\r\nHost: www.py4inf.com\r\n\r\n')

总的来说:虽然HTTP看起来很简单,但事实并非如此。不要仅仅通过查看一点流量来假设事情是如何进行的,而是遵循实际的标准。即使它一开始似乎在为特定服务器工作,但以后可能会崩溃。