python ws消息推送

  index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ws测试</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js">
</script>
    <script>
            var ws = new WebSocket('ws:localhost:10000/websocket');
            ws.onopen = function(evt){
                console.log("on open");
            }
            ws.onclose = function(evt){
                console.log("on close");
            }
            ws.onmessage = function(evt){
               $("#vals").append(evt.data);
            }
        </script>
</head>
<body>
<div id="vals"></div>
</body>
</html>

aap.py

pip install bottle
pip install bottle-websocket 

from bottle import route, run, static_file
from bottle.ext.websocket import GeventWebSocketServer
from bottle.ext.websocket import websocket
import time

@route("/")
def callback():
    return static_file("websocket.html", root=".")

@route("/websocket", apply=[websocket])
def callback(ws):
    count = 0
    while True:
        count += 1
        time.sleep(1)
        ws.send(str(count))

run(host='localhost', port=10000, server=GeventWebSocketServer)

评论

刷新

友情链接