【问题标题】:python multiprocessing Listener shutdownpython多处理监听器关闭
【发布时间】:2018-10-26 18:28:34
【问题描述】:

我正在尝试创建一个侦听器,连接客户端,并在一段时间后强制关闭套接字并终止连接。即使尝试关闭套接字本身,我也无法关闭连接。我不确定我做错了什么。 我的代码有一个服务器端代码和一个客户端代码(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

【问题讨论】:

    标签: python-2.7 sockets multiprocessing


    【解决方案1】:

    这是一个socket 相关问题。

    简而言之,您不能在close 之后使用shutdown,因为close 会破坏套接字(文件描述符)。

    thisthis 中的详细信息。

    【讨论】:

    • 感谢您的回答。其实我没有打电话后关机。这些是我在不同的执行中分别尝试过的所有方法。我会改写我的问题以减少混淆
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多