我试图创建一个侦听器,连接客户端,并在一段时间后强制关闭套接字并终止连接。即使尝试关闭套接字本身,我也无法关闭连接。我不确定自己在做什么错。 我的代码有一个服务器端代码和一个客户端代码(2个不同的终端)
from multiprocessing.connection import Listener
import threading, socket
def start_thread(name, target, args=(), kwargs={}, daemon=True):
thread = threading.Thread(name=name, target=target, args=args, kwargs=kwargs)
thread.daemon = daemon
thread.start()
return thread
# client
received = []
def child(conn):
while True:
msg = conn.recv()
received.append(msg)
# this just echos the value back, replace with your custom logic
#import time
#time.sleep(5)
conn.send(msg)
# server
serv = Listener(('', 5000), authkey='mypassword')
def mother(serv):
while True:
client = serv.accept()
print(client, type(client))
t = start_thread('child', child, kwargs={'conn':client})
print(t)
start_thread('mother',mother, (serv,))
from multiprocessing.connection import Client
c = Client(('localhost', 5000), authkey='mypassword')
c.send('hello');print( c.recv())
c.send({'a': 123}); print('i am back', c.recv())
现在在服务器端,无需关闭终端或退出python,我想停止监听程序并关闭套接字。通过尝试以下所有操作(分别在不同的运行时中),没有任何效果,并且连接仍处于打开状态
1 - serv.close()
2 - serv._listener.close()
3 - serv._listener._socket.close()
# Shutdown the socket always returns an error
4 - socket.socket.shutdown(serv._listener._socket, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 174, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
5 - serv._listener._socket.shutdown(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 174, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor