异常
python的socket模块实际上定义了4种可能出现的异常:
1)与一般I/O 和通信问题有关的socket.error;
2)与查询地址信息有关的socket.gaierror;
3)与其他地址错误有关的socket.herror;
4)与在一个socket上调用settimeout()后,处理超时有关的socket.timeout;
import socket, sys, time host = sys.argv[1] textport = sys.argv[2] filename = sys.argv[3] #创建socket对象 try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, e: print 'Strange error creating socket:%s' % e sys.exit(1) #创建端口号 try: port = int(textport) except ValueError: try: port = socket.getservbyname(textport, 'tcp') except socket.error, e: print 'Couldn not find your port:%s' % e sys.exit(1) #连接socket try: s.connect((host, port)) except socket.gaierror, e: print 'Address-related error connecting to server :%s' % e sys.exit(1) except socket.error, e: print 'Connection error:%s' % e sys.exit(1) fd = s.makefile('rw', 0) #使用文件类对象 print 'sleeping...' time.sleep(10) #线程休息10S print 'Continuing...' try: s.sendall("GET %s HTTP/1.0 " % filename) except socket.error, e: print 'Error sending data:%s' % e sys.exit(1) try: fd.flush() except socket.error, e: print 'Error sending data: %s' % e sys.exit(1) try: s.shutdown(1) s.close() except socket.error, e: print 'Error sending data:%s' % e while True: 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)
另外,数据只有在您调用了shutdown()函数后才能确保被发送。
try: s.shutdown(1) s.close() except socket.error, e: print 'Error sending data:%s' % e
flush()调用,从技术层面来看,因为makefile()的调用聪明的没有地址缓冲器(buffer),所以这个调用并不是必须的,但是如果因为某个原因而使用了缓冲器,则需要调用。
try: fd.flush() except socket.error, e: print 'Error sending data: %s' % e sys.exit(1)