#!/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\r\n\r\n" % 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()        

 

展示

python之优雅处理套接字错误

 

end!

 

相关文章:

  • 2022-12-23
  • 2022-01-15
  • 2021-06-04
  • 2021-06-15
  • 2022-12-23
  • 2021-05-17
  • 2021-06-02
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-01
  • 2022-12-23
  • 2021-10-08
相关资源
相似解决方案