# server-
# pip install geventwebsocket
# pip install flask
from flask import Flask, render_template, request
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket # 用来确定WebSocket对象
app = Flask(__name__)
user_socket_list = []
@app.route('/ws')
def ws():
# 来回收发信息
# 一个用户的长链接wsgi.websocket
user_socket = request.environ.get("wsgi.websocket") # type:WebSocket
while 1:
# 接收消息
msg = user_socket.receive()
print(msg)
try:
user_socket.send(msg)
except:
return '123'
@app.route('/')
def index():
return render_template("many_person.html")
if __name__ == '__main__':
http_server = WSGIServer(("0.0.0.0", 7000), app, handler_class=WebSocketHandler)
http_server.serve_forever()
many_person.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script type="application/javascript">
var ws = new WebSocket("ws://127.0.0.1:7000/ws");
{#通过onopen函数向服务端发送消息#}
ws.onopen = function(){
ws.send("hello")
};
ws.onmessage = function (ws_status) {
console.log(ws_status.data)
}
</script>
</html>