Python瓶和gevent服务器是异步运行的吗?

时间:2017-08-24 00:20:31

标签: python asynchronous websocket bottle gevent

我最近一直在研究具有歌曲请求功能的网络控制扬声器,我似乎无法同时将两个浏览器连接到Web Socket。服务器仍将为浏览器提供HTML,但不提供Web Socket提供的数据。我知道我可能需要使用gevent的内置greenlets,但我不知道这里是否适用,或者我是否需要重新考虑我对无限循环的想法。有人可以帮忙吗?

gevent-test.py的内容:

from bottle import request, Bottle, abort, static_file
app = Bottle()

open("playlist2.txt").close()

@app.route('/websocket')
def handle_websocket():
    wsock = request.environ.get('wsgi.websocket')
    if not wsock:
        abort(400, 'Expected WebSocket request.')

    while True:
        try:
            playlist = open("playlist2.txt", "r").readlines()
            playlistnew = open("playlist.txt", "r").readlines()
        except FileNotFoundError:
            pass
        except PermissionError:
            pass
        if playlist != playlistnew:
            try:
                playlist = open("playlist2.txt", "w")
                playlist.writelines(playlistnew)
                playlist.close()
            except FileNotFoundError:
                pass
            try:
                message = open("playlist2.txt", "r").read()
                print(message)
                wsock.send(message)
            except WebSocketError:
                break

@app.get('/home')
def homepage():
    return static_file("index.html", root=".")

from gevent.pywsgi import WSGIServer
from geventwebsocket import WebSocketError
from geventwebsocket.handler import WebSocketHandler
server = WSGIServer(("127.0.0.1", 8080), app,
                    handler_class=WebSocketHandler)
server.serve_forever()

index.html的内容:

<!DOCTYPE html>
<html>
<head>
  <h1>Now playing:</h1>
  <p id="now-playing"></p>
  <h1>Up Next:</h1>
  <table>
        <thead>
            <tr>
                <th>No.</th>
                <th>Song Title</th>
            </tr>
        </thead>
        <tbody id="playlist">

        </tbody>
  </table>
  <script type="text/javascript">
    var ws = new WebSocket("ws://127.0.0.1:8080/websocket");
    ws.onopen = function() {};
    ws.onmessage = function (evt) {
        var file = (evt.data).split("\n");
        console.log(file);
        var table = document.getElementById("playlist");
        table.innerHTML = '';
        document.getElementById("now-playing").innerHTML = file[0]
        for(var i=1, len=file.length; i < len; i++){
            var number = (i);
            var name = (file[i]);
            console.log(file[i])
            console.log(i)
            var newrow = table.insertRow(-1);
            var numberCell = newrow.insertCell(0);
            numberCell.innerHTML = number
            var nameCell = newrow.insertCell(1);
            nameCell.innerHTML = name
        };
    };
  </script>
</head>
</html>

playlist.txt和playlist2.txt可以包含您想要的任何内容,但是当您编辑和保存playlist.txt时,Web套接字仅提供数据。然后它编辑playlist2.txt以匹配,然后获取新数据并发送它。

0 个答案:

没有答案