I have read Bottle + WebSocket and the Github project bottle-websocket, but they all use gevent, or other third party tools. Question: nowadays (2023), is there a way to do a simple Bottle + WebSocket hello world example, without any third party tool? This is a beginning but it fails (see JS console) with: (index):12 WebSocket connection to 'ws://127.0.0.1:5000/ws' failed import bottle, random app = bottle.Bottle() @bottle.route("/") def index(): return bottle.static_file("index.html", root=".") @bottle.route("/ws") def ws(): wsock = bottle.request.environ.get('wsgi.websocket') if not wsock: print('Expected WebSocket request.') while True: try: message = wsock.receive() wsock.send("Your message was: %r" % message) except: break bottle.run(threaded=False, port=5000, debug=True) HTML+JS code for index.html: <html> <body> <div> hello </div> <script> var ws = new WebSocket("ws://127.0.0.1:5000/ws"); ws.onopen = () => { ws.send("Hello, world"); }; ws.onmessage = (evt) => { console.log(evt.data); }; </script> </body> </html>
Currently, as of my knowledge cutoff in September 2021, the Bottle framework itself does not provide native WebSocket support. To handle WebSocket connections in Bottle without relying on third-party libraries, you would need to implement the WebSocket protocol manually.
The WebSocket protocol involves an initial HTTP handshake and then transitioning to a persistent connection between the client and the server. This process requires managing the low-level details of the protocol, which can be quite complex.
However, I can provide you with an example using the Python
socket
module to create a simple WebSocket server within your Bottle application. Please note that this approach is a basic demonstration and may not be suitable for production use. Here’s an example of how you could modify your code:In this example, we manually handle the WebSocket handshake by constructing the necessary HTTP headers and sending them back to the client. The
ws()
function reads and sends WebSocket messages using the low-level socket operations.Keep in mind that manually implementing the WebSocket protocol can be error-prone and may not support all the features provided by third-party WebSocket libraries. If possible, using a well-maintained library like
gevent-websocket
orwebsocket-server
is generally recommended for WebSocket functionality in a Bottle application.