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.一次请求,一次响应 ...
 
随机推荐
- ${__setProperty 等常见jmeter参数相关博客汇总
			
jmeter 控制线程组执行顺序 这个要配合全局变量.if和while来实现BeanShell取样器,全局变量:${__setProperty(newswitch,${switch1},)}if条 ...
 - PAT甲级 堆 相关题_C++题解
			
堆 目录 <算法笔记>重点摘要 1147 Heaps (30) 1155 Heap Paths (30) <算法笔记> 9.7 堆 重点摘要 1. 定义 堆是完全二叉树,树中每 ...
 - php 之分页
			
$a=$_FILES; // print_r($a);die; foreach ($a as $key => $value) { $k=$key; } // $_FILES['license'] ...
 - Linux十大顶级发行版本
			
当前顶级发行版概览 对于Linux新手来说,在各发行版之间困惑得进行选择和不断增加的数量实在令人头晕.这就是写作本文的原因,其中列出的10个(附加一个值得一提的FreeBSD,BSD一族中最为流行 ...
 - asp.net core-4.命令行配置
			
先用vs2017创建一个控制台应用程序,这里不做多的介绍. 现在命名空间中添加using Microsoft.Extensions.Configuration; 如果没有,就在依赖项—>管理Nu ...
 - ftp-server(对象存储)
			
1.背景 在腾讯云弄了一个对象存储,想通过ftp上传照片 说明连接: 腾讯云:https://cloud.tencent.com/document/product/436/7214 GitHub:ht ...
 - redis哈希表数据类型键的设置
			
命令名称:hset 语法:hset key field value 功能: 1)将哈希表key中的域field的值设为value. 2)如果key不存在,一个新的哈希表被创建并进行hset操作. 3) ...
 - (五)lucene之特定项搜索和查询表达式
			
需求:模糊搜索. 前提: 本例中使用lucene 5.3.0 package com.shyroke.lucene; import java.io.File; import java.io.File ...
 - (二十二)SpringBoot之使用mybatis generator自动生成bean、mapper、mapper xml
			
一.下载mybatis generator插件 二.生成generatorConfig.xml new一个generatorConfig.xml 三.修改generatorConfig.xml 里面的 ...
 - 十三、Vue中的computed属性
			
以下抄自https://www.cnblogs.com/gunelark/p/8492468.html 看了网上很多资料,对vue的computed讲解自己看的都不是很清晰,今天忙里抽闲,和同事们又闲 ...