多处理中的套接字侦听器客户端未退出

时间:2019-01-19 06:10:21

标签: python sockets multiprocessing

想编写一个具有多处理功能的套接字客户端,下面的代码有什么想法吗? 我不必用python编写服务器,但是我需要在监听之前在本地主机上生成一个空闲端口。该端口将以其他代码发送到服务器。 我也期望下面的代码每隔1秒钟打印出一条消息,以进行调试,但它只打印一次。而且即使我设置了stop事件,该过程也没有加入。

def getsocket():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('', 0))
        return s
    except Exception as err:
        return None


def PortListener(s, stopper):
    print("Listensing to port for message")
    while not stopper.is_set():
        time.sleep(1)
        print("check message..")
        message = s.recv(4096)
        if message:
            print("received message: {}".format(message))


def logprogress():
    s = getsocket()
    port = s.getsockname()[1]
    print("port number: {}".format(str(port)))
    s.connect(("localhost", port))
    stopper = mp.Event()
    logger = mp.Process(target=PortListener, args=(s, stopper))
    logger.start()
    return logger, stopper


def stopprogress(logger, stopper):
    if logger and stopper:
        print("Stopping listening to worker's progress.")
        stopper.set()
        logger.join()
        print("Exit process")
    else:
        raise TypeError

if __name__ == '__main__':
    logger, stopper = logprogress()
    time.sleep(10)
    stopprogress(logger, stopper)

0 个答案:

没有答案