简体   繁体   English

我在这个 python 练习中遇到了一些麻烦

[英]I am having some trouble in this python exercise

I have a problem with this exercise, here is the exercise:我对这个练习有问题,这是练习:

Change your socket program so that it counts the number of characters, it has received and stops displaying any text after it has shown 3000 characters.更改您的套接字程序,使其计算字符数,它已接收并在显示 3000 个字符后停止显示任何文本。 The program should retrieve the entire document and count the total number of characters and display the count of the number of characters at the end of the document.程序应该检索整个文档并计算总字符数并在文档末尾显示字符数计数。

Original Code:原始代码:

import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)
while True:
data = mysock.recv(512)
if len(data) < 1:
break
print(data.decode(),end='')
mysock.close()

MY CODE:我的代码:

import socket
url=input("Enter a URL :\n")
count=0
host_name=url.split("/")[2]
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    mysock.connect((host_name, 80))
    cmd=('GET url HTTP/1.0\n\n'.encode())
    mysock.send(cmd)
except:
    print("Enter a valid URl")
exit()


while True:
    data = mysock.recv(512)
    count=count+len(data)
    if len(data) < 1:
        break
    print(data.decode())
mysock.close()

My output:我的输出:

Enter a URL :
http://www.py4inf.com/code/romeo.txt
HTTP/1.1 400 Bad Request
Server: nginx
Date: Mon, 06 May 2019 10:29:37 GMT
Content-Type: text/html
Content-Length: 166
Connection: close

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx</center>
</body>
</html>

I am getting an error Message " 400 Bad request"我收到一条错误消息“400 Bad request”

Can anyone help me, Thank you谁能帮帮我,谢谢

This code worked for me:这段代码对我有用:

import socket
from urllib.parse import urlsplit

url = urlsplit('http://www.py4inf.com/code/romeo.txt')
host = url.hostname
path = url.path

request = f'GET {path} HTTP/1.1\nHost: {host}\n\n'.encode('utf-8')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, 80))
s.send(request)
result = s.recv(10000)
while (len(result) > 0):
    print(result.decode('utf-8'))

And here is the output of above code:这是上面代码的输出:

 HTTP/1.1 200 OK
 Content-Type: text/plain
 Content-Length: 167
 Connection: keep-alive
 Keep-Alive: timeout=15
 Date: Thu, 09 May 2019 08:49:50 GMT
 Server: Apache
 Last-Modified: Fri, 04 Dec 2015 19:05:04 GMT
 ETag: "a7-526172f58b800"
 Accept-Ranges: bytes
 Cache-Control: max-age=604800, public
 Access-Control-Allow-Origin: *
 Access-Control-Allow-Headers: origin, x-requested-with, content-type
 Access-Control-Allow-Methods: GET

 But soft what light through yonder window breaks
 It is the east and Juliet is the sun
 Arise fair sun and kill the envious moon
 Who is already sick and pale with grief

Edit: here is your original code corrected:编辑:这是您更正的原始代码:

import socket
from urllib.parse import urlsplit

url = urlsplit(input("Enter a URL: ").strip())
count = 0
host = url.hostname
path = url.path
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    print(f'Connecting to {host} and fetching {path}')
    s.connect((host, 80))
    cmd = f'GET {path} HTTP/1.1\nHost: {host}\n\n'.encode('utf-8')
    s.send(cmd)
except:
    print("Enter a valid URl")
    exit()

while True:
    data = s.recv(512)
    count += len(data)
    if len(data) < 1:
        break
    print(data.decode())

s.close()

And here is the output I'm getting using the above code:这是我使用上述代码得到的输出:

Enter a URL: http://www.py4inf.com/code/romeo.txt
Connecting to www.py4inf.com and fetching /code/romeo.txt
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 167
Connection: keep-alive
Keep-Alive: timeout=15
Date: Thu, 09 May 2019 15:30:16 GMT
Server: Apache
Last-Modified: Fri, 04 Dec 2015 19:05:04 GMT
ETag: "a7-526172f58b800"
Accept-Ranges: bytes
Cache-Control: max-age=604800, public
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: origin, x-requested-with, content-type
Access-Control-Allow-Methods: GET

But soft what light through yonder window breaks
It is the east and Juliet 
is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief

Try this, running on Python 3试试这个,在 Python 3 上运行

import socket

url = input("Enter a URL :")
try:
    host_name = url.split("/")[2]
    mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    mysock.connect((host_name, 80))
    s = 'GET '+url+' HTTP/1.0\r\n\r\n'
    cmd = s.encode()
    mysock.send(cmd)
except:
    print("Enter a valid URl")
    exit()

count=0
while True:
    data = mysock.recv(512)
    for c in data:
        count += 1
    if count > 3000 or len(data) < 1:
        break
    #print(data.decode())
print(count)
mysock.close()

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

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