我正在尝试创建一个简单的asyncore示例,其中一个套接字是发送方,另一个是接收方。由于某些原因,接收器上的handle_read()从未被调用过,因此我从未获得过“测试”数据。有人知道为什么吗?这是我第一次尝试asyncore,所以它可能是非常简单的东西。
import asyncore, socket, pdb, random
class Sender(asyncore.dispatcher):
def __init__(self):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
def handle_connect(self):
print ('first connect')
def writable(self):
True
def readable(self):
return False
def handle_write(self):
pass
def handle_close(self):
self.close()
class Receiver(asyncore.dispatcher):
def __init__(self):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
def handle_connect(self):
print ('first connect')
def readable(self):
return True
def handle_read(self):
print 'reading'
def handle_write(self):
print 'write'
def handle_accept(self):
self.conn_sock, addr = self.accept()
print 'accepted'
def handle_close(self):
self.close()
a = Sender()
b = Receiver()
addr = ('localhost', 12344)
b.bind(addr)
b.listen(1)
a.connect(addr)
asyncore.loop()
a.send('test')发布于 2009-10-17 16:18:43
asyncore.loop不会终止,所以a.send不会发生,因为您已经将其编码为在asyncore.loop退出后按行发生。
一旦解决了这个问题,你就会遇到这样的问题:你在单个线程和进程中运行发送者和接收者,所以除非你采取非常微妙的步骤来确保每件事都以正确的顺序发生,否则你将会死锁。asyncore当然是为了在独立运行的进程之间使用,所以这个问题不会出现在正常的、真实的使用中。如果您对在何处发生死锁感到好奇,可以制作自己的asyncore副本,并在其中添加print语句,或者尝试
python -m trace -t ast.py不幸的是,后者提供了大量的输出,并且没有显示关键变量的值。因此,虽然尝试起来没有痛苦和非侵入性,但它远不如一些有策略地放置的print(例如,在每次选择之前和之后的r和w fd列表)。
我相信(但没有深入调试过它,因为这是一个不切实际的场景),select触发器只触发一次(因为在第一次select之前接受/连接和将字节写入套接字,它们都会“崩溃”成一个事件),但是这个事件的处理不能知道崩溃(在正常使用中是不会发生的!),所以它只处理接受/连接。但是,如果您花时间进行更深入的调试,您无疑会更好地理解这种异常场景!
发布于 2012-06-27 20:46:51
因为Alex指出了原因,所以延迟了很多,并且没有解决问题,但您的代码显示:
def writable(self):
True 这不应该是:
def writable(self):
return True https://stackoverflow.com/questions/1582558
复制相似问题