Created
March 13, 2014 10:56
-
-
Save oberstet/9526275 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
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