Skip to content

Instantly share code, notes, and snippets.

@oberstet
Created March 13, 2014 10:56
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 oberstet/9526275 to your computer and use it in GitHub Desktop.
Save oberstet/9526275 to your computer and use it in GitHub Desktop.
from autobahn.asyncio.websocket import WebSocketServerProtocol, \
WebSocketServerFactory
import asyncio
import json
def fastsquare(x):
return x * x
def slowsquare(x):
asyncio.sleep(2)
return x * x
class SlowSquareServerProtocol(WebSocketServerProtocol):
@asyncio.coroutine
def onOpen(self):
print("WebSocket connection open.")
@asyncio.coroutine
def onMessage(self, payload, isBinary):
print payload
if not isBinary:
obj = json.loads(payload)
try:
if obj[2] == "little" :
res = slowsquare(obj[3]["valeur"])
else :
res = fastsquare(obj[3]["valeur"])
except Exception as e:
print e
self.sendClose(1000, str(e))
else:
obj = json.dumps(res).encode('utf8')
print (str(obj))
self.sendMessage(json.dumps(res).encode('utf8'))
if __name__ == '__main__':
import asyncio
factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
factory.protocol = SlowSquareServerProtocol
loop = asyncio.get_event_loop()
coro = loop.create_server(factory, 'localhost', 9000)
server = loop.run_until_complete(coro)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
server.close()
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment