Flask实现简单的群聊和单聊
Flask是使用python写的一个简单轻量级的框架,今天我们使用Flask实现一个简单的单聊和群聊功能 .

主要思路 : 前端登录聊天室,聊天室信息包含用户的登录信息,相当于一个登录功能,会把这个信息记录在url中发送给后端,后端会把登录信息作为识别用户的标志,url中的信息会作为key值存在一个字典中:
{'111': <geventwebsocket.websocket.WebSocket object at 0x000001AB31716118>, '222': <geventwebsocket.websocket.WebSocket object at 0x000001AB317160B0>}
单聊也是基于这个key值实现的,如果发送的用户为空则默认为群聊;
一.导入相关的包并实例化一个Flask对象
import json from flask import Flask, request, render_template
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket app = Flask(__name__) #实例化一个Flask对象
user_socket_dict = {} #创建一个空字典
二.后端通过request.environ获取前端的所有信息,其中wsgi.websocket对应的值即用户对象,取出这个对象存入字典 :
@app.route('/ws_app/<user_nick>') #设置Flask路由,前端通过访问这个地址拆解信息,<user_nick>即前端登录聊天室输入的内容
def ws_app(user_nick):
user_socket = request.environ.get("wsgi.websocket") # type:WebSocket #取出environ中的wsgi.websocket对应的值
user_socket_dict[user_nick] = user_socket #以<user_nick>为key在字典中插入用户信息
print(user_socket_dict) #{'111': <geventwebsocket.websocket.WebSocket object at 0x000001AB31716118>, '222': <geventwebsocket.websocket.WebSocket object at 0x000001AB317160B0>}
三.通过receive取出用户要发送的内容并进行json转换,通过get方法取出to_user(要发送的对象的聊天号),如果没有返回0,后边再通过if判断区别单聊还是群聊:如果to_user存在,说明要发给单个用户,否则是群发.
while True:
msg = user_socket.receive() #取出发送内容 msg_dict = json.loads(msg)
to_user = msg_dict.get("to_user",0) #没有返回0
if to_user: #有发送对象 单聊
to_user_socket = user_socket_dict.get(to_user) #用get方法取出
to_user_socket.send(msg)
else: #没有发送对象 群聊
for usocket in list(user_socket_dict.values()):
usocket.send(msg) @app.route('/')
def index():
return render_template('my_ws.html') if __name__ == '__main__':
http_serve = WSGIServer(('0.0.0.0', 9527), app, handler_class=WebSocketHandler)
http_serve.serve_forever()
四.前端代码
<body>
<p><input type="text" id="nick">
<button onclick="login()">登陆聊天室</button>
</p>
发送给:<input type="text" id="to_user">消息:<input type="text" id="send_str">
<button id="send_btn" onclick="send()">发送消息</button>
<p>
<div id="chat_list"> </div>
</p>
</body>
<script type="application/javascript">
var ws = null;
function login() {
var nick = document.getElementById("nick").value;
ws = new WebSocket("ws://192.168.***.***:9527/ws_app/" + nick);
ws.onmessage = function (messageEvent) {
console.log(messageEvent.data);
var ptag = document.createElement("p"); var message = JSON.parse(messageEvent.data); ptag.innerText = message.from_user + " : " + message.message;
document.getElementById("chat_list").appendChild(ptag);
};
} function send() {
var message = document.getElementById("send_str").value;
var send_str = {
from_user: document.getElementById("nick").value,
to_user: document.getElementById("to_user").value,
message: message
};
var json_send_str = JSON.stringify(send_str);
ws.send(json_send_str);
}
</script>
Flask实现简单的群聊和单聊的更多相关文章
- 如何用WebSocket实现一个简单的聊天室以及单聊功能
百度百科中这样定义WebSocket:WebSocket协议是基于TCP的一种新的网络协议.它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端.简单的说,We ...
- 一套高可用、易伸缩、高并发的IM群聊、单聊架构方案设计实践
一套高可用.易伸缩.高并发的IM群聊.单聊架构方案设计实践 一套高可用.易伸缩.高并发的IM群聊.单聊架构方案设计实践-IM开发/专项技术区 - 即时通讯开发者社区! http://www.52im. ...
- WebSocket群聊与单聊
一 . WebSocket实现群聊 py文件代码 # py文件 from flask import Flask, render_template, request from geventwebsock ...
- Websocket实现群聊、单聊
Websocket 使用的第三方模块:gevent-websocket 群聊 ws群聊.py中的内容 from flask import Flask, request, render_template ...
- websocket实现群聊和单聊(转)
昨日内容回顾 1.Flask路由 1.endpoint="user" # 反向url地址 2.url_address = url_for("user") 3.m ...
- Flask+WebSocket实现群聊与单聊功能
在开始我们的程序代码之前,先来了解一下相关的基础知识: 1.什么是websocket? (1)WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议.WebSocket ...
- spring websocket 和socketjs实现单聊群聊,广播的消息推送详解
spring websocket 和socketjs实现单聊群聊,广播的消息推送详解 WebSocket简单介绍 随着互联网的发展,传统的HTTP协议已经很难满足Web应用日益复杂的需求了.近年来,随 ...
- flask + websocket实现简单的单聊和群聊
单聊 from flask import Flask,request,render_template from geventwebsocket.handler import WebSocketHand ...
- flask 第五章 WebSocket GeventWebsocket 单聊群聊 握手 解密 加密
1.WebSocket 首先我们来回顾一下,我们之前用socket学习过的项目有: 1.django 2.flask 3.FTP - 文件服务 HTTP - TCP (特点): 1.一次请求,一次响应 ...
随机推荐
- python3.7 完美安装
在安装python3.7的过程中,我发现如果不加注意,pip3是无法被安装的.而这就不能算是完整安装python3了. 所以,我总结一下,如何完美安装python3.7. 依赖 yum insta ...
- Centos7.0配置Hadoop2.7.0伪分布式
一.ssh免密登录 1.命令ssh-keygen. overwrite输入y一路回车 2.将生成的密钥发送到本机 ssh-copy-id localhost中间会询问是否继续输入“yes” 3.测试免 ...
- python学习-42 装饰器 --- 函数闭包1
函数闭包举例: def father(name): print('hello world') def son(): print('儿子说:我的爸爸是%s' % name) def grandfson( ...
- JVM OOM异常会导致JVM退出吗?
出处: https://mp.weixin.qq.com/s/8j8YTcr2qhVActLGzOqe7Q https://blog.csdn.net/h2604396739/article/de ...
- (转)从0移植uboot (二) _uboot启动流程分析
ref:https://www.cnblogs.com/xiaojiang1025/p/6496704.html 经过了上一篇的配置,我们已经执行make就可以编译出一个uboot.bin,但这还不够 ...
- redis 缓存对象、列表
在spring boot环境下有个StringRedisTemplate对象,默认已经为我们配置好了,只需要自动注入过来就能用,但是使用它只能在Redis中存放字符串.具体操作如下: @RunWith ...
- MySQL 子查询(三) 派生表、子查询错误
From MySQL 5.7 ref:13.2.10.8 Derived Tables 八.派生表 派生表是一个表达式,用于在一个查询的FROM子句的范围内生成表. 例如,在一个SELECT查询的FR ...
- SSL Virtual Servers
SSL Virtual Servers 来源 https://www.carlstalhood.com/ssl-virtual-servers-netscaler-12/ SSL Virtual Se ...
- vscode 基本知识以及如何配置 C++ 环境
参考: 在用VSCode? 看完这篇文章, 开发效率翻倍!最后一条厉害了~ Visual Studio Code(VS code)你们都在用吗?或许你们需要看一下这篇博文 按下 ctrl+K,再按下 ...
- 关于Vue中,checkBox等组件在赋值后,点击切换页面未及时更新问题
我们经常碰到这样的问题,在v-for循环中,给某些组件(此处以checkBox为例)赋值后,组件并不能正常切换, 这是因为数据层太多,render函数没有自动更新,需手动强制刷新. 解决方法:在切换c ...