实验1:实现初始的通信
客户端:用浏览器向服务端发送信息
服务端:首先接收浏览器发来的信息,并作出相应应答
第一步:需要导入模块:
from flask import Flask,request
from geventwebsocket.websocket import WebSocket
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
第二步:HTML客户端设置
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>浏览器模拟发送信息简单实现,websocket通信</title> </head> <body> </body> <script type="text/javascript"> var ws = new WebSocket("ws://127.0.0.1:9527/ws"); ws.onmessage=function (data) { console.log(data.data); } </script> </html>
第三步:服务端设置
#先导入一下模块
from flask import Flask,request from geventwebsocket.websocket import WebSocket from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer
#创建一个flask对象 app=Flask(__name__) @app.route("/index") def index(): return "欢迎进入index界面" #websocket验证函数 @app.route('/ws') def ws(): print(request.environ) user_socket = request.environ.get("wsgi.websocket") #type:WebSocket print(user_socket) #<geventwebsocket.websocket.WebSocket object at 0x043A4298> while 1: msg=user_socket.receive() user_socket.send("hello") if __name__ == '__main__': http_serv = WSGIServer(("0.0.0.0", 9527), app, handler_class=WebSocketHandler)
#始终保持运行(用于长期交互状态) http_serv.serve_forever()
演示鲜果图如下: