我正在编写一个需要在两台电脑之间进行通信的程序。我知道如何连接和发送消息给对方。当用户打开程序时,它应该监听连接。但是,如果用户点击“连接”,程序应该停止侦听连接并改为连接到用户。我应该怎么做呢?
我现在已经做到了这一点:
主要
@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()
答案 0 :(得分: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!")