我有一个简单的例子:
import socket
import time
TCP_IP = '127.0.0.1'
TCP_PORT = 81
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
while True:
s.send(bytes('hello', 'UTF-8'))
time.sleep(1)
s.close()
如果我丢失了与服务器的连接,我该如何检测,以及如何安全地重新连接呢?
是否有必要等待服务器的回答?
更新:
import socket
import time
TCP_IP = '127.0.0.1'
TCP_PORT = 81
BUFFER_SIZE = 1024
def reconnect():
toBreak = False
while True:
s.close()
try:
s.connect((TCP_IP, TCP_PORT))
toBreak = True
except:
print ("except")
if toBreak:
break
time.sleep(1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
while True:
try:
s.send(bytes('hello', 'UTF-8'))
print ("sent hello")
except socket.error as e:
reconnect()
time.sleep(1)
s.close()
如果我断开连接,它会引发错误(并不重要),然后转到 重新连接循环。但在我恢复连接后,连接会返回此错误:
OSError:[WinError 10038]尝试对非套接字
的操作进行操作如果我重新启动调用相同s.connect((TCP_IP,TCP_PORT))的脚本,它可以正常工作。
答案 0 :(得分:7)
如果连接丢失或是[Errno 104] Connection reset by peer
或ECONNRESET
的任何来电,您将获得socket.error
:send()
例外(又名recv()
)断开。因此要检测到这一点,只需捕获该异常:
while True:
try:
s.send(bytes('hello', 'UTF-8'))
except socket.error, e:
if e.errno == errno.ECONNRESET:
# Handle disconnection -- close & reopen socket etc.
else:
# Other error, re-raise
raise
time.sleep(1)
答案 1 :(得分:1)
尝试重新连接时使用新套接字。
def connect():
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
return s.makefile('w')
except socket.error as e:
log("socket error {} reconnecting".format(e))
time.sleep(5)
dest = connect()
while True:
line = p.stdout.readline()
try:
dest.write(line)
dest.flush()
except socket.error as e:
log("socket error {} reconnecting".format(e))
dest = connect()