Skip to content

Instantly share code, notes, and snippets.

@sckn
Forked from tatiana/secure_websocket.py
Last active August 29, 2015 14:17
Show Gist options
  • Save sckn/78be353d0180ed01a004 to your computer and use it in GitHub Desktop.
Save sckn/78be353d0180ed01a004 to your computer and use it in GitHub Desktop.
"""
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