Created
May 8, 2010 07:22
-
-
Save kzk/394421 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from twisted.internet import reactor | |
from twisted.internet import protocol | |
import msgpack | |
class UserHandler: | |
def hello0(self): | |
print "hello!" | |
return 0 | |
def hello1(self, a): | |
print "hello1!!" | |
print a | |
return 1 | |
class MessagePackRPCProtocol(protocol.Protocol): | |
def __init__(self): | |
self.packer = msgpack.Packer() | |
self.unpacker = msgpack.Unpacker() | |
def dataReceived(self, data): | |
if len(data) <= 0: | |
return | |
self.unpacker.feed(data) | |
for msg in self.unpacker: | |
reply = self.messageReceived(msg) | |
def messageReceived(self, msg): | |
if len(msg) != 4: | |
raise Exception("Invalid Protocol") | |
msgtype = msg[0] | |
if msgtype != 0: | |
raise Exception("request needed, but requested other type") | |
msgid = msg[1] | |
method = msg[2] | |
args = msg[3] | |
result = self.callMethod(method, args) | |
response = self.packer.pack([1, msgid, None, result]) | |
self.transport.write(response) | |
def callMethod(self, method, args): | |
try: | |
func = getattr(handler, method) | |
except AttributeError: | |
raise Exception("missing function") | |
if not callable(func): | |
raise Exception("function not callable") | |
if len(args) == 0: | |
return func() | |
else: | |
return func(args) | |
class MessagePackRPCFactory(protocol.Factory): | |
protocol = MessagePackRPCProtocol | |
def __init__(self, userHandler): | |
self.userHandler = userHandler | |
def buildProtocol(self, addr): | |
t = protocol.Factory.buildProtocol(self, addr) | |
t.userHandler = self.userHandler | |
return t | |
handler = UserHandler() | |
factory = MessagePackRPCFactory(handler) | |
reactor.listenTCP(1985, factory) | |
reactor.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment