Environment
Python 2.7
bottle==0.12.9
gevent==1.1.2
gevent-websocket==0.9.5
greenlet==0.4.10
Desired Behaviour
On executing a Bottle route, from a getJSON()
request of a single user on the frontend of a website, I want to utilise WebSockets to send data back to update a div in the front end of the website, which is visible to all users.
Current Behaviour
After implementing the steps below, I am getting Python errors from tail -100 /var/log/apache2/error.log
which ends in:
[wsgi:error] [pid 8953:tid 140138351044352] [client 127.0.0.1:32820] LoopExit: ('This operation would block forever', <Hub at 0x7f746570d7d0 epoll default pending=0 ref=0 fileno=13 resolver=<gevent.resolver_thread.Resolver at 0x7f74656737d0 pool=<ThreadPool at 0x7f7465615210 0/1/10>> threadpool=<ThreadPool at 0x7f7465615210 0/1/10>>)
What I've Tried
I am following this official brief Bottle example to include WebSocket functionality in an existing Python 2.7 Bottle application.
This is the relevant Python code I have:
from bottle import route, post, default_app, template, view, TEMPLATE_PATH, response, request, static_file, install, redirect, abort
application=default_app()
@route('/websocket')
def handle_websocket():
wsock = request.environ.get('wsgi.websocket')
if not wsock:
abort(400, 'Expected WebSocket request.')
while True:
try:
message = wsock.receive()
wsock.send("Your message was: %r" % message)
except WebSocketError:
break
from gevent.pywsgi import WSGIServer
from geventwebsocket import WebSocketError
from geventwebsocket.handler import WebSocketHandler
server = WSGIServer(("127.0.0.1", 8080), application,
handler_class=WebSocketHandler)
server.serve_forever()
Following this answer, I added the following above the last section of imports:
from gevent import monkey, sleep
monkey.patch_all()
And the same error occurred after a sudo systemctl restart apache2.service
:
[wsgi:error] [pid 9252:tid 140619290474240] [client 127.0.0.1:33322] LoopExit: ('This operation would block forever', <Hub at 0x7fe45f274c30 epoll default pending=0 ref=0 fileno=13 resolver=<gevent.resolver_thread.Resolver at 0x7fe45f1bfa10 pool=<ThreadPool at 0x7fe45f18a110 0/1/10>> threadpool=<ThreadPool at 0x7fe45f18a110 0/1/10>>)
And via virtualenv I have installed:
pip install gevent
pip install gevent-websocket
Javascript
WebSockets, and the related terminology, are new to me, so I am just trying to get the simple example working and then build from there.
$(document).on("click",".my_class, function () {
var ws = new WebSocket("ws://localhost:8080/websocket");
ws.onopen = function() {
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
});