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!

原文地址:https://www.cnblogs.com/changbo/p/5892541.html