首页 > 解决方案 > 如何让客户端套接字在失去连接后重新连接?

问题描述

我的服务器向客户端发送消息,客户端打印它们。我通过添加一个函数来重新连接客户端,该函数检查连接是否有错误,如果有,它会重新创建套接字并再次连接。服务器还有一个检查连接错误的功能,如果有,它会接受一个新的。但是,在该客户端不再接受消息并且服务器引发 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

非常感谢您的反馈;)

标签: pythonsocketsbroken-pipe

解决方案


推荐阅读