Last active
June 27, 2023 16:58
-
-
Save timsavage/d412d9e321e9f6d358abb335c8d41c63 to your computer and use it in GitHub Desktop.
Simple example of a websocket server with Tornado
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
# 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() |
How do I send to the websocket?
MDN have great docs on using WebSockets see https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications
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
@timsavage the "application" variable must be changed to "app" when setup this server 😄