py4e第12章第1题
Change the socket program socket1.py to prompt the user for the URL so
it can read any web page. You can use split(’/’) to break the URL into
its component parts so you can extract the host name for the socket
connect call. Add error checking using try and except to handle the
condition where the user enters an improperly formatted or non-existent URL.
#socket1.py
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()
我根据题目要求改了之后:
import socket
wangzhi=input('请输入网址:')
wangzh=wangzhi.split('/')[2]
cm = 'GET '+wangzhi
cmd=cm.encode()
print(wangzhi)
print(wangzh)
print(cm)
print(cmd)
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
mysock.connect((wangzh, 80))
print('1')
except:
print('网址打错了,傻逼')
quit()
try:
mysock.send(cmd)
print('2')
except:
print('cmd发送失败')
quit()
c=0
while True:
print(c)
c=c+1
data = mysock.recv(512)
print(data)
if len(data) < 1:
break
print(data.decode(),end='')
mysock.close()
运行的结果:
现在大概可以知道是卡在data = mysock.recv(512)这句,上网搜了一下也搜不到为啥会卡住。