关于Python3.5中recv()的疑问

一段代码:

import argparse
import socket
import sys
from binascii import hexlify def main: # setup argument parsing parser=argparse.ArgumentParserdescription=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.socketsocket.AF_INET,socket.SOCK_STREAM except socket.error as err_msg: printError creating socket: %s %err_msg sys.exit1 # Second try-except block -- connect to given host/port try: s.connecthost,port except socket.gaierror as err_msg: printAddress-related error connecting to server: %s %err_msg sys.exit1 except socket.error as err_msg: printConnection error: %s %err_msg sys.exit1 # Third try-except block -- sending data try: s.sendallbytesGET %s HTTP/1.1 Host:%s %filename,host,utf8 except socket.error as err_msg: printError sending data: %s %err_msg sys.exit1 while 1: # Fourth try-except block -- waiting to receive data from remote host try: buf=s.recv2048 except socket.error as err_msg: printError receiving data: %s %err_msg sys.exit1 if not lenbuf: break # write the received data sys.stdout.writebuf.decodeutf-8 s.close if __name__ == __main__: main

如果这段写成:

sys.stdout.writebuf

无法正确将收到的html文件在浏览器中解析
但是写成:

sys.stdout.writebuf.decodeutf-8

又会提示:

UnicodeDecodeError: utf-8 codec cant decode byte 0xe9 in position 2047: unexpected end of data

请问,在Python3.5中,recv得到的内容如何正确处理并输出?

sys.stdout.writebuf.decodeutf-8
你能保证发送过来的文件的编码一定是utf-8
改成别的编码试试看~ 例如:gbk


因为解码出来的内容里面有这个: <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>(部分解码是成功的,也显示出来了,但是解着解着就失败了)
成长中的程序猿

把解码语句移到循环外~

 buffer = [] while 1: # Fourth try-except block -- waiting to receive data from remote host try: buf=s.recv2048 except socket.error as err_msg: printError receiving data: %s %err_msg sys.exit1 if not lenbuf: break # write the received data buffer.appendbuf s.close sys.stdout.writeb.joinbuffer.decodeutf-8

发表评论

电子邮件地址不会被公开。 必填项已用*标注