我有一个simpletcp示例:
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()
Run Code Online (Sandbox Code Playgroud)
如果我丢失了与服务器的连接,我该如何检测,以及如何安全地重新连接呢?
是否有必要等待服务器的答案?
更新:
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()
Run Code Online (Sandbox Code Playgroud)
如果我断开连接,它会引发错误(并不重要),然后进入重新连接循环.但在我恢复连接后,连接会返回此错误:
OSError:[WinError 10038]尝试对非套接字的操作进行操作
如果我重新启动调用相同s.connect((TCP_IP,TCP_PORT))的脚本,它可以正常工作.
在任何调用或连接丢失或断开连接时,您将获得socket.error:[Errno 104] Connection reset by peerexception(aka ECONNRESET).所以为了检测它,只需捕获该异常: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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17531 次 |
| 最近记录: |