像Adobe ActionScript中那样的Python客户端套接字事件处理
我正在把一些ActionScript代码转换成Python,但在实现一个类似于Flash中事件调度器的功能时遇到了困难(flash.events.EventDispatcher)。
我需要创建一个客户端套接字连接到服务器,服务器会返回一个横幅。然后客户端会发送一些信息,接收新的横幅等等。
我知道怎么创建客户端套接字,但问题在于如何处理事件,以便客户端根据不同的事件运行相应的函数。
我看过一些模块,比如Asyncore和Twisted,老实说,我希望找到一个快速且容易实现的方案。我需要尽量简单地完成代码转换,以便做一个概念验证。
这是我使用asyncore的部分代码:
import socket
import asyncore
class Client(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host, port))
def handle_connect(self):
self.log('Socket connected')
def handle_close(self):
print "Socket disconnected"
self.close()
def handle_read(self):
print 'Received: ', self.recv(1024)
self.handle_close()
def connect(host, port)
clientSocket = Client(host, port)
asyncore.loop()
出于某种原因,代码返回了以下错误:
warning: unhandled write event
warning: unhandled write event
warning: unhandled write event
...
上面的代码现在还没有做什么有用的事情。我需要为IO错误和处理来回发送的数据添加事件处理程序。不过,首先我需要把基础搞清楚。
任何帮助都非常感谢。谢谢。