Socket模块常见的异常有:
Socket.error 与一般I/O和通信问题有关的
Socket.gaierror 与查询地址有关的
Socket.herror 与其他地址错误有关
Socket.timeout 与一个socket上调用settimeout()后,超时处理有关
1 socket.error
import socket
try:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error,e:
print 'Strange error creating socket:%s' %e
创建套接字,接收发送信息数据时候的异常一般由socket.error来处理
>>> import socket
>>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> s.connect(('wang',71625))
Traceback (most recent call last):
gaierror: (11001, 'getaddrinfo failed')
import socket,sys
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
except socket.gaierror,e:
print 'Error connecting to server: %s' % e
结果为:
>>>
Error connecting to server: (11001, 'getaddrinfo failed')
>>>
下面演示了一个服务器端得例子
import socket,traceback
host=''
port=51423
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt((socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))
s.listen(1)
while 1: