python - 如何让客户端套接字在失去连接后重新连接?
问题描述
我的服务器向客户端发送消息,客户端打印它们。我通过添加一个函数来重新连接客户端,该函数检查连接是否有错误,如果有,它会重新创建套接字并再次连接。服务器还有一个检查连接错误的功能,如果有,它会接受一个新的。但是,在该客户端不再接受消息并且服务器引发 BrokenPipeError 之后。
服务器:
import socket
import sys
import time
import threading
s = socket.socket()
ip = "localhost"
port = 7000
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((ip, port))
s.listen(100)
def help():
print("h = help | q = quit server | b = go back")
print("message = type message | quit = quit the client")
help()
print("")
print("Waiting for connections....")
c, addr = s.accept()
def checkConnection():
while socket.error:
try:
c, addr = s.accept()
except:
time.sleep(2)
threading.Thread(target=checkConnection).start()
def main():
while True:
msg = input("Input> ")
if msg == "q":
sys.exit(0)
elif msg == "h":
help()
elif msg == "quit":
c.send(bytes(msg, 'utf-8'))
elif msg == "message":
c.send(bytes(msg, 'utf-8'))
while True:
message = input("Message: ")
if message == "b":
c.send(bytes(message, 'utf-8'))
main()
c.send(bytes(message, 'utf-8'))
main()
客户:
import socket
import threading
import time
import sys
c = socket.socket()
ip = "localhost"
port = 7000
c.connect((ip, port))
def checkConnection():
while socket.error:
try:
c = socket.socket()
ip = "localhost"
port = 7000
c.connect((ip, port))
except:
time.sleep(2)
threading.Thread(target=checkConnection).start()
def main():
while True:
msg = c.recv(1024).decode()
if msg == "message":
while True:
message = c.recv(1024).decode()
if message == "b":
main()
else:
print(message)
elif msg == "quit":
print("Goodbye!")
break
main()
错误:
Traceback (most recent call last):
File "server.py", line 42, in <module>
main()
File "server.py", line 41, in main
c.send(bytes(message, 'utf-8'))
BrokenPipeError: [Errno 32] Broken pipe
非常感谢您的反馈;)
解决方案
推荐阅读
- python-3.5 - python 3.5 在树莓派 3 中安装 pyscard
- sql - 必须声明标量变量pivot sql查询
- javascript - 如何在单击时交替 jquery 切换滑动动作
- flutter - 异步映射不反映方法主体的变化
- mysql - 选择计数查询需要 2 分钟才能在 mysql 中得到计数结果
- javascript - js拆分数组在单词之间添加空格(不是第一个)
- java - java.lang.ClassNotFoundException: org.springframework.dao.support.PersistenceExceptionTranslator
- android - 如何在新的 Google In App Purchase 中处理具有购买历史记录的购买状态
- ios - 从设置中删除沙盒帐户(iOS 13.0 问题)
- ios - dequeueReusableCell 导致文本改变颜色