Python - 判断用户是服务器还是客户端

0 投票
1 回答
510 浏览
提问于 2025-04-18 07:00

我正在写一个程序,需要让两台电脑之间进行通信。我知道怎么连接并互相发送消息。当用户打开程序时,它应该监听连接。但是如果用户点击“连接”,程序就应该停止监听连接,而是连接到一个用户。我要怎么做到这一点呢?
我现在的代码是这样的:

主程序

@threaded
def getOnline(self):
   # fires when the user opens the program
    client.connect(PORT)

@threaded
def connect(self):
    # when the user clicks connect
    global IS_MASTER
    IS_MASTER = True
    print('Master:', IS_MASTER)
    if IS_MASTER:
        client.closeConnection()
        server.connect(CLIENT_IP, PORT)

客户端

class Client():

    def __init__(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def connect(self, port):
        print('Listening to connections')
        self.s.bind(('', port))
        self.s.listen(1)
        conn, addr = self.s.accept()
        print('Connected by:', addr)

    def closeConnection(self):
        print('Not listening any longer')
        self.s.close()
        sys.exit()

服务器

class Server():

    def __init__(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def connect(self, host, port):
        self.s.connect((host, port))
        print('Connected to:', host)

现在当我点击“连接”时,我收到的错误是:“ConnectionAbortedError: [Errno 53] 软件导致连接中止”。

任何帮助都会非常感激!

编辑
完整的错误追踪信息

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/threading.py", line 639, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/threading.py", line 596, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/cedricgeerinckx/Dropbox/Redux/OSX/Redux.py", line 28, in wrapped_f
    ret = f(*args, **kwargs)
  File "/Users/cedricgeerinckx/Dropbox/Redux/OSX/Redux.py", line 204, in getOnline
    client.connect(PORT)
  File "/Users/cedricgeerinckx/Dropbox/Redux/OSX/Client.py", line 14, in connect
    conn, addr = self.s.accept()
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/socket.py", line 135, in accept
    fd, addr = self._accept()

1 个回答

0

这个错误是在你的 getOnline 方法里面出现的,而这个方法是在程序启动时运行的。这意味着,当 connect 方法关闭连接时,就会发生这个错误。你应该在 getOnline 方法内部处理这个错误:

@threaded
def getOnline(self):
   # fires when the user opens the program
    try:
        client.connect(PORT)
    except ConnectionAbortedError as e:
        print("Connection shut down!")

撰写回答