zoukankan      html  css  js  c++  java
  • python之优雅处理套接字错误

    #!/usr/local/bin/python3.5
    #coding:utf-8
    
    import sys
    import socket
    import argparse
    
    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 e:
            print("error creating socket:" % e)
            sys.exit(1)
            
        #Second try-except block -- connect to given host/PORT
        try:
            s.connect((host, port))
        except socket.gaierror as e:
            print("address-related error connectiong to server : %s" % e )
            sys.exit(1)
        except socket.error as e:
            print("connection error: %s" % e)
            sys.exit(1)
        
        #third try-except block -- sending data
        try:
            s.sendall(("GET %s HTTP/1.0
    
    " % filename).encode(encoding='utf-8'))
        except socket.error as e:
            print("Error sending data: %s" % e)
            sys.exit(1)
            
        while 1:
            #Fourth tr-except block --waiting to receive data from remote host
            try:
                buf = str(s.recv(2048), 'utf-8')
            except socket.error as e:
                print("error receiving data: %s" % e)
                sys.exit(1)
            if not len(buf):
                break
            # write the received data
            sys.stdout.write(buf)       
            
    if __name__ == '__main__':
        main()        

    展示

    end!

  • 相关阅读:
    docker介绍和简单使用
    docker 安装
    流畅的python python 序列
    mysql设计表结构数据类型的选择
    Mysql存储引擎的选择
    Linux python3安装/shell脚本/if/循环/函数
    LINUX 文件/组/帮助/权限/文件压缩/管道
    Linux介绍和基本命令
    如何安装secureCRT8.1破解
    centos7 终端修改字体大小
  • 原文地址:https://www.cnblogs.com/changbo/p/5892541.html
Copyright © 2011-2022 走看看