环境
Python 2.7
bottle==0.12.9
gevent==1.1.2
gevent-websocket==0.9.5
greenlet==0.4.10
所需行为
在执行Bottle路由时,从网站前端的单个用户的getJSON()
请求开始,我想利用WebSockets发送数据以更新网站前端的div,对所有用户可见。
当前行为
执行以下步骤后,我收到来自tail -100 /var/log/apache2/error.log
的Python错误,结尾于:
[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>>)
我尝试过什么
我正在关注此官方brief Bottle example,以在现有的Python 2.7 Bottle应用程序中包含WebSocket功能。
这是我的相关Python代码:
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()
在this answer之后,我在导入的最后一部分上面添加了以下内容:
from gevent import monkey, sleep
monkey.patch_all()
在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>>)
通过virtualenv我安装了:
pip install gevent
pip install gevent-websocket
的Javascript
WebSockets和相关的术语对我来说是新的,所以我只是想让简单的例子工作,然后从那里构建。
$(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);
};
});