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!

  • 相关阅读:
    链表中环的入口节点
    链表中倒数第k个节点
    调整数组顺序使奇数位于偶数前面
    53. Maximum Subarray
    42. Trapping Rain Water
    48. Rotate Image
    css技巧一
    html语义
    label标签表单响应
    CSS清除浮动
  • 原文地址:https://www.cnblogs.com/changbo/p/5892541.html
Copyright © 2011-2022 走看看