Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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