socketio无法在Flask应用程序中运行?

时间:2015-03-02 04:11:35

标签: python websocket flask socket.io

我正在编写一个小型Flask Web服务器,我正在使用Flask-SocketIO,但websocket无法正常工作?我找不到原因。

这是我的代码:

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return render_template('index.html', lines=[], currentTime=datetime.utcnow())
    else:
        buy_report = os.path.join(DIR_PATH, 'buy_report')
        with open(buy_report, 'r') as fread:
            lines = fread.read().decode('gbk').split("\n\n")
            return render_template('index.html', lines = lines, currentTime=datetime.utcnow())


@socketio.on('message')
def handle_message(message):
    print('received message: ' + message)

class MyFileMonitor(FileSystemEventHandler):
    def on_modified(self, event):
        print event.src_path
        if os.path.basename(event.src_path) == r"buy_report":
            socketio.emit('fileChanged')  //HERE: ###########

if __name__ == '__main__':
    observer = Observer()
    event_handler = MyFileMonitor()
    observer.schedule(event_handler, DIR_PATH, recursive=True)
    observer.start()

    socketio.run(app)

前端代码monitor.js

$(document).ready(function () {
    var socket = io.connect('http://' + document.domain + ':' + location.port);
     socket.on('connect', function() {
                console.log('connect');
                socket.emit('message', {data: 'I\'m connected!'});
            });
});

我包含了这个'monitor.js':

{% block scripts %}
    {{ super() }}

    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
    <script type="text/javascript" src={{ url_for('static', filename = 'monitor.js') }}></script>

{% endblock %}

但是我发现console.log('connect');没有被执行。 谁能帮帮我?

0 个答案:

没有答案