0
我正在嘗試構建一個小型應用程序來學習「使用燒瓶的python網絡套接字」,我試圖計算使用該應用程序的用戶數量。爲此我使用了Matt Makai教程。我想我在搞東西,因爲櫃檯沒有遞增。Python中的網絡套接字(使用燒瓶)問題
這裏是我的HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sockets</title>
</head>
<body>
<h1>Welcome to sockets</h1>
<br>
<!--<h2> {{ counter }} visitors have seen this page!</h2>-->
<h2><span id="user-count">0</span> visitors have seen this page! </h2>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var url = "ws://localhost:5001";
var socket = new io.connect(url + "/dd");
socket.on('msg', function(msg) {
$("#connected").html(msg.count);
});
});
</script>
</body>
</html>
這是我的Python代碼:
from gevent import monkey
monkey.patch_all()
import redis
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
db = redis.StrictRedis('localhost', 6379, 0)
socketio = SocketIO(app)
@app.route('/')
def main():
# c = db.incr('counter')
return render_template('main.html')
@socketio.on('connect', namespace='/sockets')
def ws_conn():
c = db.incr('user_count')
socketio.emit('msg', {'count': c}, namespace="/sockets")
@socketio.on('disconnect', namespace='/sockets')
def ws_disconn():
c = db.decr('user_count')
socketio.emit('msg', {'count': c}, namespace="/sockets")
if __name__ == "__main__": # check only if this file is called directly (not by importing somewhere else)
socketio.run(app)