Skip to content

Instantly share code, notes, and snippets.

@amir-rahnama
Created November 20, 2015 14:43
Show Gist options
  • Save amir-rahnama/0681dd5c182fd4c4ddb4 to your computer and use it in GitHub Desktop.
Save amir-rahnama/0681dd5c182fd4c4ddb4 to your computer and use it in GitHub Desktop.
A simple Tornado (http://www.tornadoweb.org/en/stable/) WebSocket Server (with Client)
var ws = new WebSocket("ws://localhost:8888");
ws.onopen = function() {
ws.send("Hello, world");
};
//When Client Received a Message
ws.onmessage = function(evt) {
console.log(evt.data);
};
import tornado.websocket
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def check_origin(self, origin):
return True
def open(self):
print("WebSocket opened")
def on_message(self, message):
self.write_message(u"You said: " + message)
def on_close(self):
print("WebSocket closed")
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", WebSocketHandler)
]
tornado.web.Application.__init__(self, handlers)
def main():
tornado.options.parse_command_line()
app = Application()
app.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment