织梦CMS - 轻松建站从此开始!

沙龙国际_沙龙国际亚洲第一品牌网上娱乐

当前位置: 主页 > 沙龙365 >

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

时间:2017-07-09 06:51来源:未知 作者:admin 点击:
一段代码: import argparseimport socketimport sysfrom binascii import hexlifydef main(): # setup argument parsing parser=argparse.ArgumentParser(description='Socket Error Examples') parser.add_argument('--host',action='store',dest='hos

一段代码:

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

织梦二维码生成器
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
推荐内容