关于Python3.5中recv()的疑问
一段代码:
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()得到的内容如何正确处理并输出?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
sys.stdout.write(buf.decode('utf-8'))
你能保证发送过来的文件的编码一定是
utf-8
?改成别的编码试试看~ 例如:
gbk
把解码语句移到循环外~