赞
踩
一段代码:
import argparse
import socket
import sys
from binascii import hexlify
def main():
# setup argument parsing
parser=argparse.ArgumentParser(description='Socket Error Examples')
parser.add_argument('--host',action='store',dest='host',required=False)
parser.add_argument('--port',action='store',dest='port',type=int,required=False)
parser.add_argument('--file',action='store',dest='file',required=False)
given_args=parser.parse_args()
host=given_args.host
port=given_args.port
filename=given_args.file
# First try-except block -- create socket
try:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error as err_msg:
print('Error creating socket: %s' %err_msg)
sys.exit(1)
# Second try-except block -- connect to given host/port
try:
s.connect((host,port))
except socket.gaierror as err_msg:
print('Address-related error connecting to server: %s' %err_msg)
sys.exit(1)
except socket.error as err_msg:
print('Connection error: %s' %err_msg)
sys.exit(1)
# Third try-except block -- sending data
try:
s.sendall(bytes('GET %s HTTP/1.1\r\n\r\nHost:%s' %(filename,host),'utf8'))
except socket.error as err_msg:
print('Error sending data: %s' %err_msg)
sys.exit(1)
while 1:
# Fourth try-except block -- waiting to receive data from remote host
try:
buf=s.recv(2048)
except socket.error as err_msg:
print('Error receiving data: %s' %err_msg)
sys.exit(1)
if not len(buf):
break
# write the received data
sys.stdout.write(buf.decode('utf-8'))
s.close()
if __name__ == '__main__':
main()
如果这段写成:
sys.stdout.write(buf)
无法正确将收到的html文件在浏览器中解析
但是写成:
sys.stdout.write(buf.decode('utf-8'))
又会提示:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 2047: unexpected end of data
请问,在Python3.5中,recv()得到的内容如何正确处理并输出?
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。