之前我们制定了一个很简单的RPC消息 的格式,但是还遗留了两个问题,上一篇解决掉了一个,还留下一个
class Request(object): def __str__(self): return str({'id':self.id, 'command':self.command, 'parameter':self.parameter})
@classmethod def encode(cls, message): if isinstance(message, Request): return str(message) elif isinstance(message, Response): return str(message) elif isinstance(message, Notification): return str(message) else: raise Exception('unknown type when encode')
@classmethod def decode(cls, data): info = eval(data) if 'command' in info: request = Request() request.id = info.get('id') request.command = info.get('command') request.parameter = info.get('parameter', {}) return request elif 'result' in info: response = Response() response.id = info.get('id') response.result = info.get('result') return response elif 'message' in info: note = Notification() note.message = info.get('message') return note else: raise Exception('unknown data when decode')
版权声明:本文为博主原创文章,未经博主允许不得转载。
一个简单RPC框架是如何炼成的(IV)——实现RPC消息的编解码
原文地址:http://blog.csdn.net/crylearner/article/details/46900203