当前位置:   article > 正文

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

python 输出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()得到的内容如何正确处理并输出?

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/156974
推荐阅读
相关标签
  

闽ICP备14008679号