Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5076445
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2011-11-21 14:54:51

使用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
阅读(1087) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~