Websocket
2021-03-04 17:28
标签:协议 null display view socket ide ebs insecure err 需要将run,wsgi替换成websocket Websocket 标签:协议 null display view socket ide ebs insecure err 原文地址:https://www.cnblogs.com/Pythonzrq/p/13259887.htmlflask中的socket
群聊
# 不需要记住 但是要知道是什么模块驱使Flask 支持Websocket
# gevent-websocket
# 以下代码 和 gevent-websocket 使用方式 请记录在案
from geventwebsocket.handler import WebSocketHandler
from geventwebsocket.server import WSGIServer
from geventwebsocket.websocket import WebSocket # 语法提示
from flask import Flask, request, render_template
app = Flask(__name__)
socket_list = []
@app.route("/ws")
def ws():
sock = request.environ.get("wsgi.websocket") # type:WebSocket
socket_list.append(sock)
print(socket_list)
# 1 : 连接打开
# 2 : 客户端主动关闭连接
# 3 : 连接关闭 由服务器发起
# 0 : 连接中。。。。。。
while 1:
try:
msg = sock.receive() # hello
except:
socket_list.remove(sock)
break
for so in socket_list:
if so == sock:
continue
try:
so.send(msg)
except:
continue
return "200OK"
# return "200 OK"
@app.route("/")
def index():
return render_template("ws_client.html")
if __name__ == ‘__main__‘:
# app.run()
http_serv = WSGIServer(("0.0.0.0", 9527), app, handler_class=WebSocketHandler) # environment
http_serv.serve_forever()
"""
{‘GATEWAY_INTERFACE‘: ‘CGI/1.1‘, ‘SERVER_SOFTWARE‘: ‘gevent/1.4 Python/3.6‘, ‘SCRIPT_NAME‘: ‘‘, ‘wsgi.version‘: (1, 0), ‘wsgi.multithread‘: False, ‘wsgi.multiprocess‘: False, ‘wsgi.run_once‘: False, ‘wsgi.url_scheme‘: ‘http‘, ‘wsgi.errors‘: <_io.textiowrapper name="‘<stderr">‘ mode=‘w‘ encoding=‘UTF-8‘>, ‘SERVER_NAME‘: ‘DESKTOP-U8U37NO‘, ‘SERVER_PORT‘: ‘9527‘, ‘REQUEST_METHOD‘: ‘GET‘, ‘PATH_INFO‘: ‘/ws‘, ‘QUERY_STRING‘: ‘‘, ‘SERVER_PROTOCOL‘: ‘HTTP/1.1‘, ‘REMOTE_ADDR‘: ‘127.0.0.1‘, ‘REMOTE_PORT‘: ‘56107‘, ‘HTTP_HOST‘: ‘127.0.0.1:9527‘, ‘HTTP_USER_AGENT‘: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0‘, ‘HTTP_ACCEPT‘: ‘text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8‘, ‘HTTP_ACCEPT_LANGUAGE‘: ‘zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2‘, ‘HTTP_ACCEPT_ENCODING‘: ‘gzip, deflate‘, ‘HTTP_CONNECTION‘: ‘keep-alive‘, ‘HTTP_UPGRADE_INSECURE_REQUESTS‘: ‘1‘, ‘wsgi.input‘:
DOCTYPE html>
html lang="zh-CN">
head>
meta charset="utf-8">
meta http-equiv="X-UA-Compatible" content="IE=edge">
meta name="viewport" content="width=device-width, initial-scale=1">
title>Bootstrap 101 Templatetitle>
head>
body>
h1>你好,世界!h1>
input type="text" id="text"> button id="send">点击发送消息button>
div id="content_list">
div>
body>
script type="application/javascript">
var ws = new WebSocket("ws://192.168.14.26:9527/ws");
// 回调函数
// onopen websocket连接建立完成 status == 1
// ws.onopen = function () {
// ws.send("Hello");
// };
// onmessage websocket 接收到消息时 执行
ws.onmessage = function (eventMessage) {
var s = eventMessage.data;
var p = document.createElement("p");
p.innerText = s;
document.getElementById("content_list").appendChild(p);
};
// ws.onclose
// ws.send("123");
document.getElementById("send").addEventListener("onclick",function () {
var st = document.getElementById("text").value();
ws.send(st);
})
script>
html>
点对点
import json
from geventwebsocket.handler import WebSocketHandler # ws 协议请求处理
from geventwebsocket.server import WSGIServer # 替换Flask 原有的WSGI
from geventwebsocket.websocket import WebSocket # 语法提示
from flask import Flask, request, render_template
app = Flask(__name__)
socket_dict = {}
@app.route("/ws/
DOCTYPE html>
html lang="zh-CN">
head>
meta charset="utf-8">
meta http-equiv="X-UA-Compatible" content="IE=edge">
meta name="viewport" content="width=device-width, initial-scale=1">
title>Bootstrap 101 Templatetitle>
head>
body>
h1>你好,世界!h1>
你的名字:input type="text" id="username">button id="createws">登录聊天室button>
p>给input type="text" id="recv">发送input type="text" id="text">内容 button id="send">点击发送消息button>p>
div id="content_list">
div>
body>
script type="application/javascript">
var ws = null;
document.getElementById("createws").onclick = function () {
var username = document.getElementById("username").value;
ws = new WebSocket("ws://192.168.14.26:9527/ws/"+username);
ws.onopen = function () {
alert("欢迎进入九聊");
};
ws.onmessage = function (eventMessage) {
var msg = JSON.parse(eventMessage.data);
console.log(msg);
var p = document.createElement("p");
p.innerText = msg.sender + " : " + msg.msg;
document.getElementById("content_list").appendChild(p);
};
};
// 回调函数
// onopen websocket连接建立完成 status == 1
// ws.onopen = function () {
// ws.send("Hello");
// };
// onmessage websocket 接收到消息时 执行
// ws.onclose
// ws.send("123");
document.getElementById("send").onclick = function () {
var recv = document.getElementById("recv").value;
var msg = document.getElementById("text").value;
var sender = document.getElementById("username").value;
var send_msg = {
"sender":sender,
"recv": recv,
"msg":msg
};
console.log(send_msg);
ws.send(JSON.stringify(send_msg));
};
script>
html>