Error Handling Example With Shutdown and File-Like Objects : Error Handling « Network « Python Tutorial






import socket, sys, time

host = "127.0.0.1"
textport = 80
filename = "test.txt"

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    port = int(textport)
    s.connect((host, port))
    fd = s.makefile('rw', 0)

    time.sleep(10)

    fd.write("GET %s HTTP/1.0\r\n\r\n" % filename)
    fd.flush()

    s.shutdown(1)
except socket.error, e:
    print "Error sending data (detected by shutdown): %s" % e
    sys.exit(1)

while 1:
    try:
        buf = fd.read(2048)
    except socket.error, e:
        print "Error receiving data: %s" % e
        sys.exit(1)
    if not len(buf):
        break
    sys.stdout.write(buf)








21.6.Error Handling
21.6.1.Error Handling Example With Shutdown
21.6.2.Error Handling Example With Shutdown and File-Like Objects
21.6.3.Server With Error Handling