Skip to content

Instantly share code, notes, and snippets.

@lvh
Created June 14, 2012 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lvh/2933162 to your computer and use it in GitHub Desktop.
Save lvh/2933162 to your computer and use it in GitHub Desktop.
"""
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