django-websocket 安装及配置
1、安装 dwebsocket
(venv) C:\code_object\websocketTest>pip install dwebsocket -i https://pypi.douban.com/simple
2、当前项目环境
python版本
1 (venv) C:\code_object\websocketTest>python --version 2 Python 3.4.4
django版本
1 (venv) C:\code_object\websocketTest>pip list dwebsocket 2 Django (1.10) 3 dwebsocket (0.5.5) 4 pip (9.0.1) 5 setuptools (28.8.0) 6 six (1.11.0)
3、相关代码
urls.py
1 from django.conf.urls import url, include 2 3 from websocketTest import views 4 urlpatterns = [ 5 url(r'^websocket/', views.websocket_test), 6 url(r'^echo/', views.echo), 7 ]
views.py
1 from dwebsocket import require_websocket,accept_websocket 2 import dwebsocket 3 4 from django.http.response import HttpResponse 5 from django.shortcuts import render 6 import json 7 8 import redis 9 rc = redis.StrictRedis(host='redis_host', port=6379, db=8, decode_responses=True) 10 11 12 @require_websocket # 只接受websocket请求,不接受http请求,这是调用了dwebsocket的装饰器 13 def websocket_test(request): 14 message = request.websocket.wait() 15 request.websocket.send(message) 16 17 18 @accept_websocket # 既能接受http也能接受websocket请求 19 def echo(request): 20 if not request.is_websocket(): 21 try: 22 print('---- request.GET 数据:--->>',request.GET) 23 message = request.GET['message'] 24 return HttpResponse(message) 25 26 except Exception as e: 27 print('---- 报错: e--->>',e) 28 return render(request,'test_websocket/user2.html') 29 30 else: 31 redis_my_key = '' 32 while True: 33 # print(dir(request.websocket)) 34 # print('request.websocket.count_messages() -->', request.websocket.count_messages()) 35 if request.websocket.count_messages() > 0: 36 for message in request.websocket: 37 38 print('request.websocket._get_new_messages() -->', request.websocket._get_new_messages()) 39 if request.websocket.is_closed(): 40 print('连接关闭') 41 return HttpResponse('连接断开') 42 else: 43 44 # print('request.websocket.is_closed() -->', request.websocket.is_closed()) 45 print('--- request.is_websocket() 数据: --->>',message) 46 47 # 将数据写入数据库 {"my_uuid":"1","your_uuid":"2","message":"Hello, World!"} 48 data = json.loads(message.decode()) 49 conn_type = data.get('type') 50 my_uuid = data.get('my_uuid') 51 your_uuid = data.get('your_uuid') 52 msg = data.get('message') 53 redis_my_key = 'message_{uuid}'.format(uuid=my_uuid) 54 redis_you_key = 'message_{uuid}'.format(uuid=your_uuid) 55 56 if conn_type == 'register': 57 if my_uuid and your_uuid: 58 request.websocket.send("注册成功".encode('utf-8')) 59 else: 60 request.websocket.send("uuid为空,链接断开".encode('utf-8')) 61 # request.websocket.close() 62 return HttpResponse('uuid为空,连接断开') 63 elif conn_type == 'sendMsg': 64 rc.lpush(redis_my_key, msg) 65 rc.lpush(redis_you_key, msg) 66 67 break 68 elif redis_my_key: 69 data = rc.rpop(redis_my_key) 70 if data: 71 print('收到消息,立马发送data -->', data) 72 request.websocket.send(data.encode('utf-8')) 73 74 # print(dir(request.websocket)) 75 # request.websocket.send(message + '这是您发来的 @@@ '.encode('utf-8'))
app02/user2.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>django-websocket</title> 5 <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> 6 <script type="text/javascript">//<![CDATA[ 7 $(function () { 8 $('#connect_websocket').click(function () { 9 if (window.s) { 10 window.s.close() 11 } 12 /*创建socket连接*/ 13 var socket = new WebSocket("ws://" + '127.0.0.1:8000' + "/echo/"); 14 socket.onopen = function () { 15 console.log('WebSocket open');//成功连接上Websocket 16 17 const my_uuid=$('#my_uuid').val(); 18 const your_uuid=$('#your_uuid').val(); 19 const sendData = { 20 type: 'register', 21 my_uuid, 22 your_uuid, 23 }; 24 window.s.send(JSON.stringify(sendData)); 25 }; 26 27 socket.onmessage = function (e) { 28 console.log('message: ' + e.data);//打印出服务端返回过来的数据 29 $('#messagecontainer').prepend('<p>' + e.data + '</p>'); 30 }; 31 // Call onopen directly if socket is already open 32 if (socket.readyState == WebSocket.OPEN) socket.onopen(); 33 window.s = socket; 34 }); 35 $('#send_message').click(function () { 36 //如果未连接到websocket 37 if (!window.s) { 38 alert("websocket未连接."); 39 } else { 40 const my_uuid=$('#my_uuid').val(); 41 const your_uuid=$('#your_uuid').val(); 42 const message=$('#message').val(); 43 const sendData = { 44 type: 'sendMsg', 45 my_uuid, 46 your_uuid, 47 message 48 }; 49 window.s.send(JSON.stringify(sendData));//通过websocket发送数据 50 } 51 }); 52 $('#close_websocket').click(function () { 53 if (window.s) { 54 window.s.close();//关闭websocket 55 console.log('websocket已关闭'); 56 } 57 }); 58 59 }); 60 //]]></script> 61 </head> 62 <body> 63 <br> 64 <div> 65 输入自己的ID: <input type="text" id="my_uuid" value=""/> 66 </div> 67 <div> 68 发送给谁的ID: <input type="text" id="your_uuid" value=""/> 69 </div> 70 <input type="text" id="message" value=""/> 71 <button type="button" id="connect_websocket">连接 websocket</button> 72 <button type="button" id="send_message">发送 message</button> 73 <button type="button" id="close_websocket">关闭 websocket</button> 74 <h1>Received Messages</h1> 75 <div id="messagecontainer"> 76 77 </div> 78 </body> 79 </html>
转载于:https://www.cnblogs.com/CongZhang/p/9916221.html
django-websocket 安装及配置相关推荐
- django配置在MySQL_怎么在Django中安装与配置mysql
怎么在Django中安装与配置mysql 发布时间:2021-02-26 17:42:11 来源:亿速云 阅读:57 作者:Leah 本篇文章为大家展示了怎么在Django中安装与配置mysql,内容 ...
- 【Django】安装及配置
目录 MVC框架与MTV框架 Django的MTV模式 Django框架图示 安装及配置 创建一个Django项目 目录介绍 运行Django项目 启动Django报错 模版文件配置 静态文件配置 A ...
- Django基本概念、安装、配置到实现框架,Xmind学习笔记
Django从安装.配置到实现简单web框架的基本操作流程 纯手工Xmind笔记整理: 点我下载 预览图: 如有错误,谢谢指出
- 怎么检查python是否安装成功-检查python以及django是否安装配置成功
首先说明下,我使用pycharm作为开发的IDE,在第一次创建django项目的时候,会自动安装django包的.(网上也有很多单独安装的方法),环境变量配置成功后,就是用下面的方法检测安装成功与否. ...
- django 获取环境变量_Django 安装和配置环境变量
1.在线安装Django windows 下在cmd 命令提示符当中输出以下命令 pip install Django==1.10.4 Django 会默认安装在python 目录lib\site-p ...
- 基于Ubuntu Server 16.04 LTS版本安装和部署Django之(二):Apache安装和配置
基于Ubuntu Server 16.04 LTS版本安装和部署Django之(一):安装Python3-pip和Django 基于Ubuntu Server 16.04 LTS版本安装和部署Djan ...
- Django Rest Framework - 安装,配置 与 新建 Serialization
1.安装 安装 Rest FrameWork 使用的是 pip 安装, Linux 与 Mac OS可以 安装pip进行直接操作下面命令: pip install djangorestframewor ...
- Django 安装与配置教程
文章目录 Django 安装与配置教程 一,Windows系统安装Django 1) 离线安装 2) 在线安装 3) 配置Django环境变量 4) 检查是否安装成功 二,Linux和Mac系统安装D ...
- Django安装与配置教程(图解)
Django安装与配置教程(图解) 不同 Django 版本对 Python 版本的要求也是不一样的 ,Django 对 Python 版本的支持,如表格所示: Django版本与Python版本对应 ...
- django配置环境linux,linux环境下Django的安装配置详解
linux环境下Django的安装配置详解 1. 下载安装Django pip install Django==1.6.5 测试是否安装成功 >>> import django> ...
最新文章
- poj 2288(状态压缩dp + TSP问题)
- 【mysql】str_to_date()字符串转化为日期类型
- 1.7-06编程基础之字符串 字符翻转
- 设置SecureCRT配色和解决乱码问题
- windows 上的应用性能测试
- 计算机网络操作系统课件,计算机网络操作系统课件(张浩军版).ppt
- 编写函数main求3!+6!+9!python_Python day 6(3) Python 函数式编程1
- css - 给图片添加蒙版
- java web请求转发_Javaweb请求转发及重定向实现详解
- 生产环境apache2整合tomcat动静分离
- python网课什么平台好-这些AI课网课最具人气!不仅免费、系统,还附带链接 | 资源...
- 285页解析百度、阿里、腾讯前端面试题,通关秘籍请收好!
- 单片机18b20c语言程序,单片机c语言ds18b20程序
- 从国内跳槽至新加坡工作的经验分享
- Python之爬虫 搭建代理ip池
- 网页设计中的灰色调配色技巧
- php面试时的自我称呼,求职者不知道在面试时该如何称呼hr?
- centos安装jq工具
- d3dcompiler_43.dll缺失怎么修复方法_d3dcompiler43dll丢失怎么解决
- 在二叉树中找到两个节点的最近公共祖先(C++)