Python开发【笔记】:aiohttp搭建简易聊天室
简易聊天室:
1、入口main.py
import logging import jinja2 import aiohttp_jinja2
from aiohttp import web
from aiohttpdemo_chat.views import index async def init_app(): app = web.Application() app['websockets'] = {} app.on_shutdown.append(shutdown) aiohttp_jinja2.setup(
app, loader=jinja2.PackageLoader('aiohttpdemo_chat', 'templates')) app.router.add_get('/', index) return app async def shutdown(app):
for ws in app['websockets'].values():
await ws.close()
app['websockets'].clear() def main():
# logging.basicConfig(level=logging.INFO)
logging.basicConfig(level=logging.INFO,
format="%(asctime)s [%(filename)s:%(lineno)d] %(message)s", datefmt="%m/%d/%Y %H:%M:%S [%A]") app = init_app()
web.run_app(app) if __name__ == '__main__':
main()
2、业务views.py
import logging import aiohttp
import aiohttp_jinja2
from aiohttp import web
from faker import Faker log = logging.getLogger(__name__) def get_random_name():
fake = Faker()
return fake.name() async def index(request):
ws_current = web.WebSocketResponse()
ws_ready = ws_current.can_prepare(request)
if not ws_ready.ok:
return aiohttp_jinja2.render_template('index.html', request, {}) await ws_current.prepare(request) name = get_random_name()
log.info('%s joined.', name) await ws_current.send_json({'action': 'connect', 'name': name}) for ws in request.app['websockets'].values():
await ws.send_json({'action': 'join', 'name': name})
request.app['websockets'][name] = ws_current while True:
msg = await ws_current.receive()
logging.info(msg.type)
if msg.type == aiohttp.WSMsgType.text:
for ws in request.app['websockets'].values():
if ws is not ws_current:
await ws.send_json(
{'action': 'sent', 'name': name, 'text': msg.data})
else: break del request.app['websockets'][name]
log.info('%s disconnected.', name)
for ws in request.app['websockets'].values():
await ws.send_json({'action': 'disconnect', 'name': name}) return ws_current
展示:

引用-https://github.com/lianzhilei/aiohttp-demos/tree/master/demos/chat
Python开发【笔记】:aiohttp搭建简易聊天室的更多相关文章
- php+websocket搭建简易聊天室实践
1.前言 公司游戏里面有个简单的聊天室,了解了之后才知道是node+websocket做的,想想php也来做个简单的聊天室.于是搜集各种资料看文档.找实例自己也写了个简单的聊天室. http连接分为短 ...
- 学习JavaSE TCP/IP协议与搭建简易聊天室
一.TCP/IP协议 1.TCP/IP协议包括TCP.IP和UDP等 2.域名通过dns服务器转换为IP地址 3.局域网可以通过IP或者主机地址寻找到相应的主机 4.TCP是可靠的连接,效率低,且连接 ...
- 使用Html5下WebSocket搭建简易聊天室
一.Html5WebSocket介绍 WebSocket protocol 是HTML5一种新的协议(protocol).它是实现了浏览器与服务器全双工通信(full-duplex). 现在,很多网站 ...
- python开发web服务器——搭建简易网站
参看:https://blog.csdn.net/baidu_35085676/article/details/69807145
- Express+Socket.IO 实现简易聊天室
代码地址如下:http://www.demodashi.com/demo/12477.html 闲暇之余研究了一下 Socket.io,搭建了一个简易版的聊天室,如有不对之处还望指正,先上效果图: 首 ...
- Django中使用websocket并实现简易聊天室
django使用websocket并实现简易聊天室 django默认只支持http协议 如果你想让django即支持http协议又支持websocket协议,则需要做以下配置 前期配置 前提需要安装c ...
- Laravel + Swoole 打造IM简易聊天室
最近在学习Swoole,利用Swoole扩展让PHP生动了不少,本篇就来Swoole开发一款简易的IM聊天室 应用场景:实现简单的即时消息聊天室. (一)扩展安装 pecl install swool ...
- Python开发:环境搭建(python3、PyCharm)
Python开发:环境搭建(python3.PyCharm) python3版本安装 PyCharm使用(完全图解(最新经典))
- node.js+websocket实现简易聊天室
(文章是从我的个人主页上粘贴过来的,大家也可以访问我的主页 www.iwangzheng.com) websocket提供了一种全双工客户端服务器的异步通信方法,这种通信方法使用ws或者wss协议,可 ...
随机推荐
- 【iCore1S 双核心板_ARM】例程八:ADC实验——电源监控
实验原理: STM32内部集成三个12位ADC,iCore1S的所有电源经过 电阻分压或者直接接入STM32的ADC的输出通道内,输入电流 经过高端电流检测芯片ZXCT1009F输入到ADC的输入通道 ...
- 【GMT43智能液晶模块】例程九:RTC实验——时钟显示
实验原理: STM32的实时时钟(RTC)是一个独立的定时器,有一组连续计数的 计数器,通过软件来对其进行相关的配置,可以提供时钟功能,通过修改计 数器的的值,可以调整时钟.最终通过emWin在显示屏 ...
- mac 下 使用 java运行 class 文件 总是提示 “错误: 找不到或无法加载主类”的解决方法
发现问题 切换到mac平台后,突然想写点程序运行在mac下,想到mac自带java,会方便好多.不过在这过程中遇到了麻烦: 总是提示 “错误: 找不到或无法加载主类” 工程结构 查了好久,终于找到原型 ...
- 解决:github上传时出现error: src refspec master does not match any
原因分析 引起该错误的原因是,目录中没有文件,空目录是不能提交上去的 解决方法 touch README git add README git commit -m 'first commit' git ...
- 转载:CSS垂直居中总结
原文地址:http://www.cnblogs.com/dojo-lzz/p/4419596.html 工作中遇到垂直居中问题,特此总结了一下几种方式与大家分享.本文讨论的垂直居中仅支持IE8+ 1. ...
- Intellij IDEA 2015 导入MyEClipse工程
一.步骤说明 File->New->Projet from existing sources,选择要导入的项目,并且导入项目; 打开 “open module settings”进行设置: ...
- 1分钟了解MyISAM与InnoDB的索引差异
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/z50L2O08e2u4afToR9A/article/details/82111747 <数据 ...
- 使用UWA GOT优化Unity性能和内存
优化百科: https://blog.uwa4d.com/archives/Index.html https://blog.uwa4d.com/archives/Introduction_UWAGOT ...
- Android异步处理系列文章四篇之一使用Thread+Handler实现非UI线程更新UI界面
目录: Android异步处理一:使用Thread+Handler实现非UI线程更新UI界面Android异步处理二:使用AsyncTask异步更新UI界面Android异步处理三:Handler+L ...
- 转: jvm调优参数总结
JVM里的GC(Garbage Collection)的算法有很多种,如标记清除收集器,压缩收集器,分代收集器等等,详见HotSpot VM GC 的种类 现在比较常用的是分代收集(generatio ...