Last active
January 25, 2019 08:15
-
-
Save tatiana/0abbd3eeabf314d21605 to your computer and use it in GitHub Desktop.
tornado websocket connection & cookie example
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
""" | |
Example of WebSocket receiving cookies from session. | |
# Currently using tornado==4.0.2 | |
pip install git+http://github.com/tornadoweb/tornado.git | |
Run: | |
python secure_websocket.python | |
and access online: | |
http://0.0.0.0:7471 | |
""" | |
import tornado.ioloop | |
import tornado.web | |
import tornado.websocket | |
HOST = "0.0.0.0" | |
PORT = 7471 | |
HTML = """ | |
<html> | |
<head> | |
<script language="javascript"> | |
var ws = new WebSocket("ws://%s:%d/websocket"); | |
ws.onopen = function() { | |
ws.send("Hello"); | |
}; | |
ws.onmessage = function (evt) { | |
alert(evt.data); | |
}; | |
</script> | |
</head> | |
<body> | |
<p>sample websocket with Tornado</p> | |
</body> | |
</html> | |
""" % (HOST, PORT) | |
class RootHandler(tornado.web.RequestHandler): | |
def get(self): | |
self.set_cookie("some-key", "some-value", domain=HOST) | |
self.write(HTML) | |
class WebSocketHandler(tornado.websocket.WebSocketHandler): | |
def check_origin(self, origin): | |
return True | |
def open(self): | |
print("received cookies: ", self.request.cookies) | |
print("received 'myuser': ", self.get_cookie("myuser")) | |
print "WebSocket opened" | |
def on_message(self, message): | |
self.write_message(u"You said: " + message) | |
def on_close(self): | |
print "WebSocket closed" | |
application = tornado.web.Application( | |
[ | |
(r"/", RootHandler), | |
(r"/websocket", WebSocketHandler), | |
] | |
) | |
if __name__ == "__main__": | |
application.listen(PORT) | |
print("Running app on port {}".format(PORT)) | |
tornado.ioloop.IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment