Created
June 14, 2012 21:46
-
-
Save lvh/2933162 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
""" | |
AMP over WebSockets support. | |
""" | |
import json | |
import txws | |
from twisted.internet import defer, protocol | |
from twisted.python import log | |
class Bridge(protocol.Protocol): | |
""" | |
Two-way AMP over WebSockets bridge. | |
""" | |
def __init__(self, amp): | |
self._amp = amp | |
amp.boxSender = self | |
def sendBox(self, box): | |
""" | |
Sends a box over the WebSocket as JSON. | |
""" | |
log.msg("Sending box: {}".format(box)) | |
self.transport.write(json.dumps(box)) | |
def jsonObjectReceived(self, obj): | |
""" | |
Hands the JSON object (dict) over to ampBoxReceived. | |
""" | |
log.msg("JSON object received: {}".format(obj)) | |
self._amp.ampBoxReceived(obj) | |
def dataReceived(self, data): | |
""" | |
Calls jsonObjectReceived. | |
This assumes that JSON objects will always arrive as 1 chunk. | |
""" | |
self.jsonObjectReceived(json.loads(data)) | |
class BridgeFactory(protocol.Factory): | |
""" | |
A factory for AMP over WebSockets bridges. | |
""" | |
def __init__(self, ampFactory): | |
self._ampFactory = ampFactory | |
def buildProtocol(self, addr): | |
""" | |
Builds a bridge and associates it with an AMP protocol instance. | |
""" | |
return Bridge(self._ampFactory.buildProtocol(addr)) | |
def makeFactory(ampFactory): | |
""" | |
MAkes a WebSocket factory that bridges AMP messages. | |
""" | |
return txws.WebSocketFactory(BridgeFactory(ampFactory)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment