Skip to content

Instantly share code, notes, and snippets.

@timsavage
Last active June 27, 2023 16:58
Show Gist options
  • Save timsavage/d412d9e321e9f6d358abb335c8d41c63 to your computer and use it in GitHub Desktop.
Save timsavage/d412d9e321e9f6d358abb335c8d41c63 to your computer and use it in GitHub Desktop.
Simple example of a websocket server with Tornado
# While this code still works, I would recommend using Fast API for websockets in modern applications.
# See: https://fastapi.tiangolo.com/advanced/websockets/
# Note this is targeted at python 3
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.websocket
import tornado.options
LISTEN_PORT = 8000
LISTEN_ADDRESS = '127.0.0.1'
class ChannelHandler(tornado.websocket.WebSocketHandler):
"""
Handler that handles a websocket channel
"""
@classmethod
def urls(cls):
return [
(r'/web-socket/', cls, {}), # Route/Handler/kwargs
]
def initialize(self):
self.channel = None
def open(self, channel):
"""
Client opens a websocket
"""
self.channel = channel
def on_message(self, message):
"""
Message received on channel
"""
def on_close(self):
"""
Channel is closed
"""
def check_origin(self, origin):
"""
Override the origin check if needed
"""
return True
def main(opts):
# Create tornado application and supply URL routes
app = tornado.web.Application(ChannelHandler.urls())
# Setup HTTP Server
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(LISTEN_PORT, LISTEN_ADDRESS)
# Start IO/Event loop
tornado.ioloop.IOLoop.instance().start()
if __name__ == '__main__':
main()
@AntLouiz
Copy link

AntLouiz commented Nov 7, 2018

@timsavage the "application" variable must be changed to "app" when setup this server 😄

@neilyoung
Copy link

How do I send to the websocket?

@timsavage
Copy link
Author

@timsavage
Copy link
Author

While this approach will still work, I would recommend using FastAPI, they have great docs and a howto guide on using Web Sockets
See: https://fastapi.tiangolo.com/advanced/websockets/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment