flask的websocket的简单用例
后端代码
flask Flask, render_template, request flask_socketio SocketIO, emit app (__name__, , , , ) app.config[] socketio (app) socketio.(app, ) //允许跨域 count () ()() (, ) ()count count (,) (, {count, []}) (, ) ()count count (,) (, {count, []}, ) (, ) ()() count count (, {count, }) (, ) ()() (, ) ()() __name__ socketio.(app, , , )
前端代码
index.html
<!DOCTYPE > <> <> <></> </> </> <></> <></> <></> </> <> <></> <> <><></></> </> <></> <> </> </> </> <> </> </> </> <> <></> <></> </> <></> <></> </> </>
./templates/index.js
$(document).ready(() { namespace ; socket io(namespace); $().click(() { socket.connect(); }); $().click(() { socket.disconnect(); }); socket.on(, () { alert(); }); socket.on(, () { socket.emit(, { data}); }); socket.on(, (msg, cb) { $().append( $() .text(msg.count msg.data) .html() ); (cb) cb(); }); ping_pong_times []; start_time; window.setInterval(() { start_time Date().getTime(); socket.emit(); }, ); socket.on(, () { latency Date().getTime() start_time; ping_pong_times.push(latency); ping_pong_times ping_pong_times.slice(); sum ; (i ; i ping_pong_times.length; i) sum ping_pong_times[i]; $().text( Math.round((sum) ping_pong_times.length) ); }); $().submit((event) { socket.emit(, { data$().val() }); ; }); $().submit((event) { socket.emit(, { data$().val() }); ; }); });
下面是代码
需要注意flask-socketio的版本
按照操作进行就可以了