gpt4 book ai didi

python 异步连接

转载 作者:行者123 更新时间:2023-12-01 06:14:14 24 4
gpt4 key购买 nike

有没有办法检查 asyncore 中是否建立了连接?

调用 asyncore.loop() 后,如何断开服务器之间的通信?

我可以简单地调用 close() 吗?

最佳答案

一旦调用 asyncore.loop(),控制权就会移交给运行的事件循环。

asyncore.loop() 之后的任何代码只有在事件循环关闭后才会被调用。

事件循环将对各种事件使用react并调用处理程序。 要关闭事件循环,您必须在有意义的事件处理程序之一中调用 stop。

例如:看看下面的例子。

代码来自:http://www.mechanicalcat.net/richard/log/Python/A_simple_asyncore__echo_server__example

import asyncore, socket

class Client(asyncore.dispatcher_with_send):
def __init__(self, host, port, message):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host, port))
self.out_buffer = message

def handle_close(self):
self.close()

def handle_read(self):
print 'Received', self.recv(1024)
self.close()

c = Client('', 5007, 'Hello, world')
asyncore.loop()

self.close 在事件处理程序之一 -handle_read 内调用。在这种情况下,从服务器接收到数据后。它会自行断开连接。

引用文献:

关于python 异步连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4150227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com