使用pyamf,通过socket通信,as端,通过flash.net.Socket对象writeObject方法可以将复杂的as对象传过服务器python端
pyamf中的例子代码如下:
class TimerProtocol(Protocol):
interval = 1.0 # interval in seconds to send the time
encoding = pyamf.AMF0
timeout = 300
def __init__(self):
self.started = False
self.encoder = pyamf.get_encoder(self.encoding)
self.stream = self.encoder.stream
def dataReceived(self, data):
data = data.strip()
if data == 'start':
# start sending a date object that contains the current time
if not self.started:
self.start()
....
....
dataReceived方法中data变量只能接收到字符串变量,对于自定义的as对象也转变为了字符串,
将TimerProtocol继承LineReceiver,采用 def rawDataReceived(self, data)方法,收到的原始数据也是字符串的
如何转为python对象呢?
python对象转到as端,可以用 self.encoder.writeElement(python对象)的方式成功传输,就是不清楚如何接收自定义as对象
解决过程:
通过google code search 找到 中有类似代码
整理后,dataReceived写法如下:
def dataReceived(self, data):
input = pyamf.util.BufferedByteStream(data)
decoder = pyamf.decode(input,self.encoding)
asobject=decoder.next()
print type(asobject)
----------------------------------------------------------------------
print type(asobject)输出为
说明自定义as对象传过来为 pyamf.ASObject对象
通过源码了解ASObject继承自dict ,故可通过 asobject.get("属性名") 访问自定义对象的属性
补充:
encodeData = pyamf.encode({'name':'hello','data':7876})
for obj in pyamf.decode(encodeData):
print obj
阅读(1098) | 评论(0) | 转发(0) |