Based on Python documentation, there are four socket exceptions (error, herror, gaierror, timeout). Here, I only use the socket.error only. It is used for general I/O and communication problems.
For an illustration, try the following from command line:
> python.exe socket.py google.com 80 index.html
import socket,sys # standard input host = sys.argv[1] port = sys.argv[2] filename = sys.argv[3] # error handler def errorHandler(message,e): print('{0} {1}' .format(message,e)) sys.exit(1) # create socket try: s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) except socket.error, e: errorHandler('Socket creation error: ',e) # input port manipulation try: port = int(port) except ValueError,e: errorHandler('Error port number: ',e) # connection initiation try: s.connect((host,port)) except socket.error, e: errorHandler('error socket initiation: ',e) # sending HTTP request try: s.sendall("GET %s HTTP/1.0\r\n\r\n" % filename) except socket.error, e: errorHandler('Error sending HTTP request: ',e) # receiving data from server while 1: try: buf = s.recv(2048) except socket.error, e: errorHandler('Error receiving data: ',e) if not len(buf): break sys.stdout.write(buf)
No comments:
Post a Comment