flask 第五章 WebSocket GeventWebsocket 单聊群聊 握手 解密 加密
1.WebSocket
首先我们来回顾一下,我们之前用socket学习过的项目有:
1.django
2.flask
3.FTP - 文件服务
HTTP - TCP (特点):
1.一次请求,一次响应,然后断开
2.客户端永远处于主动状态
3.服务端永远处于被动状态
4.HTTP请求是无状态的 -- 在服务器不保存客户端的信息
5.由于HTTP请求是无状态的,所以服务器无法主动找到客户端
优点 :
1.速度快
2.信息安全
3.不是特别占用资源
1.轮询:
客户端不停的向服务端发送请求,服务端不停的向客户端响应,直到客户端拿到数据为止.
劣势:
1.服务端和客户端双端资源浪费
2.带宽资源占用(带宽 : 网络连接时所能传送的最大数据流速)
3.不能保证数据的实时性
2. 长轮询:
客户端向服务端发送一个请求,服务端保持这个请求,不返回值就不响应,一定时间后,服务器抛弃这个请求或者是返回. 客户端收到请求后,立即再次发起保持连接.
在这里我们类比一个实例:
你去传达室问大爷有没有快递,大爷款待你喝茶(喝茶的时候就相当于保持连接),如果中途你想去厕所(去厕所就相当于是断开了连接),回来之后继续喝茶(再次建立保持连接).
劣势:
1.相比于轮询方式,长轮询方式只是浪费了服务器的资源
2.无法保证是数据实时性
优势:
1.相比于轮询方式,他节省了客户端的资源
2.保证数据有效
3.长连接
永久的保持连接(现在我们用的基本上都是长连接)
劣势:
对服务器的CPU要求比较高
优势:
1.节省了大量的资源(客户端和服务端的资源都节省了)
2.数据实时有效性
3.带宽资源几乎不占用
WebSocket协议 : ws协议 ws://127.0.0.1 用JavaScript封装客户端
三方 : geventWebsocket Flask
web框架 : 用来进行Http请求的处理(握手)
4.单聊
.py文件的代码如下:
import json from flask import Flask, render_template, request
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket
from geventwebsocket.exceptions import WebSocketError app = Flask(__name__) user_socket_dict = {} @app.route('/my_app')
def my_app():
return render_template('myapp.html') @app.route('/my_ws/<username>')
def my_ws(username):
user_socket = request.environ.get( 'wsgi.websocket')
# 'wsgi.websocket': <geventwebsocket.websocket.WebSocket object at 0x00000206FCDC1528>,
user_socket_dict[username] = user_socket # type:WebSocket
# print(user_socket_dict)
while 1:
try:
# 阻塞等待消息数据
msg = user_socket.receive()
# 将接收到的消息反序列化成字典
msg_dict = json.loads(msg)
# print(msg)
to_user = msg_dict.get('to_user')
to_user_socket = user_socket_dict.get(to_user)
to_user_socket.send(msg)
except WebSocketError:
user_socket_dict.pop(username)
return '有个地方错了' if __name__ == '__main__':
http_server = WSGIServer(('0.0.0.0', 9527), app, handler_class=WebSocketHandler)
http_server.serve_forever()
myapp.html 文件代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
你的名字:<input type="text" id="nkname">
<button onclick="open_chat()">登录聊天室</button>
<p>发送至<input type="text" id="to_user"></p>
消息<input type="text" id="message">
<button onclick="send_msg()">发送</button>
<div id="chat_list"> </div>
</body>
<script type="application/javascript">
var ws = null; function open_chat() {
var nkname = document.getElementById('nkname').value;
ws = new WebSocket("ws://127.0.0.1:9527/my_ws/" + nkname);
ws.onopen = function () {
alert('欢迎' + nkname + '登录对骂平台!!')
};
ws.onmessage = function (EventMessage) {
var chat = JSON.parse(EventMessage.data);
var p = document.createElement('p');
p.style.cssText = 'width : 250px; text-align:left';
p.innerText = chat.from_user + '-->' + chat.message;
document.getElementById('chat_list').appendChild(p);
};
ws.onclose = function () {
console.log('断开连接了,啥情况啊? 搞事情啊');
};
} function send_msg() {
var message = document.getElementById('message').value;
var from_user = document.getElementById('nkname').value;
var to_user = document.getElementById('to_user').value;
var send_str = {
message: message,
from_user: from_user,
to_user: to_user
};
ws.send(JSON.stringify(send_str));
var p = document.createElement('p');
p.style.cssText = "width: 250px;text-align: right";
p.innerText = send_str.message + "<-我";
document.getElementById('chat_list').appendChild(p);
} </script>
</html>
5.群聊
.py文件代码如下:
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket
from geventwebsocket.exceptions import WebSocketError from flask import Flask,render_template,request app = Flask(__name__) user_socket_list = [] @app.route("/my_app")
def my_app():
return render_template("my_app.html") @app.route("/my_ws")
def my_ws():
user_socket = request.environ.get("wsgi.websocket")
# type:WebSocket
user_socket_list.append(user_socket)
# print(len(user_socket_list),user_socket_list)
while 1:
try:
msg = user_socket.receive() # 阻塞等待消息数据
except WebSocketError:
user_socket_list.remove(user_socket)
return "good bye"
for u in user_socket_list:
if u == user_socket:
continue
try:
u.send(msg)
except :
continue if __name__ == '__main__':
# app.run()
http_serv = WSGIServer(("0.0.0.0",9527),app,handler_class=WebSocketHandler)
http_serv.serve_forever()
myapp.html文件代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="message"><button onclick="send_message()">发送</button>
<div id="chat_list"> </div>
</body>
<script type="application/javascript">
var ws = new WebSocket("ws://192.168.14.200:9527/my_ws");
ws.onmessage = function (eventMessage) {
// document.getElementById("chat_list").innerHTML += "<p>" + eventMessage.data + "</p>";
var p = document.createElement("p");
p.innerText = eventMessage.data;
document.getElementById("chat_list").appendChild(p);
}; function send_message() {
var message = document.getElementById("message").value;
ws.send(message);
} </script>
</html>
flask 第五章 WebSocket GeventWebsocket 单聊群聊 握手 解密 加密的更多相关文章
- Flask(4)- flask请求上下文源码解读、http聊天室单聊/群聊(基于gevent-websocket)
一.flask请求上下文源码解读 通过上篇源码分析,我们知道了有请求发来的时候就执行了app(Flask的实例化对象)的__call__方法,而__call__方法返回了app的wsgi_app(en ...
- spring websocket 和socketjs实现单聊群聊,广播的消息推送详解
spring websocket 和socketjs实现单聊群聊,广播的消息推送详解 WebSocket简单介绍 随着互联网的发展,传统的HTTP协议已经很难满足Web应用日益复杂的需求了.近年来,随 ...
- websocket 实现单聊群聊 以及 握手原理+加密方式
WebSocket 开始代码 服务端 群聊 # type:WebSocket 给变量标注类型 # websocket web + socket from geventwebsocket.server ...
- 基于websocket的单聊.群聊
关于ai.baidu.com的 代码: #########################################核心代码################################### ...
- WebSocket+Java 私聊、群聊实例
前言 之前写毕业设计的时候就想加上聊天系统,当时已经用ajax长轮询实现了一个(还不懂什么是轮询机制的,猛戳这里:https://www.cnblogs.com/hoojo/p/longPolling ...
- WebSocket刨根问底(三)之群聊
前两篇文章[WebSocket刨根问底(一)][WebSocket刨根问底(二)]我们介绍了WebSocket的一些基本理论,以及一个简单的案例,那么今天继续,我们来看一个简单的群聊的案例,来进一步了 ...
- jquery 第五章 jQuery操作表单与表格
1.回顾 对象.bind("事件名称",function(){ // }) 阻止冒泡事件 return false, event stopProapagation() 模拟事件 ...
- 从零一起学Spring Boot之LayIM项目长成记(六)单聊群聊的实现
文章传送门: https://my.oschina.net/panzi1/blog/1577007 并没有放弃博客园,只是 t-io 在 oschina发展.用了人家的框架,也得帮人家做做宣传是吧~~
- 从零一起学Spring Boot之LayIM项目长成记(五)websocket
前言 距离上一篇已经比较久的时间了,项目也是开了个头.并且,由于网上的关于Spring Boot的websocket讲解也比较多.于是我采用了另外的一个通讯框架 t-io 来实现LayIM中的通讯功能 ...
随机推荐
- Dataframe 多行合并为一行
原表数据: 最后4行合并为1行: def ab(df): return','.join(df.values) df = df.groupby(['股票代码','股票简称'])['所属概念'].appl ...
- 复旦高等代数 I(18级)每周一题
[问题2018A01] 计算下列 $n+1$ 阶行列式的值: $$|A|=\begin{vmatrix} 0 & 1 & 1 & \cdots & 1 \\ 1 &a ...
- Python day 05
day05 数据类型 今日内容 字典 补充 .extend() users = [1,2,3,4] people = [5,6,7,8] users.extend(people) people.ext ...
- 关于新写的js在浏览器f12的时候看不到解决办法
这是由于浏览器缓存导致的,谷歌浏览器ctrl+shift+delete快捷键到清除浏览器数据清除即可.平时经常会遇到的,所以记录下.
- list,tuple,dict,set的增删改查
数据结构 list tuple dict set 增 append insert d['key']=value add 删 pop pop(0) d.pop('name') pop re ...
- 开箱即用的VScode C++环境
对大部分人来说vscode配置c++环境十分繁琐,这里提供简单方法. 1. 下载VSCode 官方网站下载(便携版):VSCode-win32-ia32-1.32.1.zip 解压VSCode-win ...
- MySQL中select、insert、update批量操作语句
项目中经常的需要使用批量操作语句对数据进行操作,使用批量语句的时候需要注意MySQL数据库的条件限制,这里主要是数据的大小限制,这里对批量插入.批量查找及批量更新的基础操作进行下简单的汇总. 1.批量 ...
- 前端开发需要掌握的SEO的知识点
SEO 工作的目的 seo 的工作目的是为了让网站更利于让各大搜索引擎抓取和收录,增加产品的曝光率. SEO 注意事项 1. 网站 TDK 标签的设置.title,description,keywor ...
- MySQL的随机数函数rand()的使用技巧
咱们学php的都知道,随机函数rand或mt_rand,可以传入一个参数,产生0到参数之间的随机整数,也可以传入两个参数,产生这两个参数之间的随机整数. 而在mysql里,随机数函数rand不能传参, ...
- [Shiro] tutorial 1 :SecurityManager and Subject
SecurityManager是Shiro的绝对核心,不同于java.lang.SecurityManager,每个应用程序都要有一个SecurityManager. 所以我们第一件事就是配置一个Se ...