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版本
(venv) C:\code_object\websocketTest>pip list dwebsocket
Django (1.10)
dwebsocket (0.5.)
pip (9.0.)
setuptools (28.8.)
six (1.11.)
3、相关代码
urls.py
from django.conf.urls import url, include from websocketTest import views
urlpatterns = [
url(r'^websocket/', views.websocket_test),
url(r'^echo/', views.echo),
]
views.py
from dwebsocket import require_websocket,accept_websocket
import dwebsocket from django.http.response import HttpResponse
from django.shortcuts import render
import json import redis
rc = redis.StrictRedis(host='redis_host', port=6379, db=8, decode_responses=True) @require_websocket # 只接受websocket请求,不接受http请求,这是调用了dwebsocket的装饰器
def websocket_test(request):
message = request.websocket.wait()
request.websocket.send(message) @accept_websocket # 既能接受http也能接受websocket请求
def echo(request):
if not request.is_websocket():
try:
print('---- request.GET 数据:--->>',request.GET)
message = request.GET['message']
return HttpResponse(message) except Exception as e:
print('---- 报错: e--->>',e)
return render(request,'test_websocket/user2.html') else:
redis_my_key = ''
while True:
# print(dir(request.websocket))
# print('request.websocket.count_messages() -->', request.websocket.count_messages())
if request.websocket.count_messages() > 0:
for message in request.websocket: print('request.websocket._get_new_messages() -->', request.websocket._get_new_messages())
if request.websocket.is_closed():
print('连接关闭')
return HttpResponse('连接断开')
else: # print('request.websocket.is_closed() -->', request.websocket.is_closed())
print('--- request.is_websocket() 数据: --->>',message) # 将数据写入数据库 {"my_uuid":"1","your_uuid":"2","message":"Hello, World!"}
data = json.loads(message.decode())
conn_type = data.get('type')
my_uuid = data.get('my_uuid')
your_uuid = data.get('your_uuid')
msg = data.get('message')
redis_my_key = 'message_{uuid}'.format(uuid=my_uuid)
redis_you_key = 'message_{uuid}'.format(uuid=your_uuid) if conn_type == 'register':
if my_uuid and your_uuid:
request.websocket.send("注册成功".encode('utf-8'))
else:
request.websocket.send("uuid为空,链接断开".encode('utf-8'))
# request.websocket.close()
return HttpResponse('uuid为空,连接断开')
elif conn_type == 'sendMsg':
rc.lpush(redis_my_key, msg)
rc.lpush(redis_you_key, msg) break
elif redis_my_key:
data = rc.rpop(redis_my_key)
if data:
print('收到消息,立马发送data -->', data)
request.websocket.send(data.encode('utf-8')) # print(dir(request.websocket))
# request.websocket.send(message + '这是您发来的 @@@ '.encode('utf-8'))
app02/user2.html
<!DOCTYPE html>
<html>
<head>
<title>django-websocket</title>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">//<![CDATA[
$(function () {
$('#connect_websocket').click(function () {
if (window.s) {
window.s.close()
}
/*创建socket连接*/
var socket = new WebSocket("ws://" + '127.0.0.1:8000' + "/echo/");
socket.onopen = function () {
console.log('WebSocket open');//成功连接上Websocket const my_uuid=$('#my_uuid').val();
const your_uuid=$('#your_uuid').val();
const sendData = {
type: 'register',
my_uuid,
your_uuid,
};
window.s.send(JSON.stringify(sendData));
}; socket.onmessage = function (e) {
console.log('message: ' + e.data);//打印出服务端返回过来的数据
$('#messagecontainer').prepend('<p>' + e.data + '</p>');
};
// Call onopen directly if socket is already open
if (socket.readyState == WebSocket.OPEN) socket.onopen();
window.s = socket;
});
$('#send_message').click(function () {
//如果未连接到websocket
if (!window.s) {
alert("websocket未连接.");
} else {
const my_uuid=$('#my_uuid').val();
const your_uuid=$('#your_uuid').val();
const message=$('#message').val();
const sendData = {
type: 'sendMsg',
my_uuid,
your_uuid,
message
};
window.s.send(JSON.stringify(sendData));//通过websocket发送数据
}
});
$('#close_websocket').click(function () {
if (window.s) {
window.s.close();//关闭websocket
console.log('websocket已关闭');
}
}); });
//]]></script>
</head>
<body>
<br>
<div>
输入自己的ID: <input type="text" id="my_uuid" value=""/>
</div>
<div>
发送给谁的ID: <input type="text" id="your_uuid" value=""/>
</div>
<input type="text" id="message" value=""/>
<button type="button" id="connect_websocket">连接 websocket</button>
<button type="button" id="send_message">发送 message</button>
<button type="button" id="close_websocket">关闭 websocket</button>
<h1>Received Messages</h1>
<div id="messagecontainer"> </div>
</body>
</html>
django-websocket 安装及配置的更多相关文章
- 【Django】安装及配置
目录 MVC框架与MTV框架 Django的MTV模式 Django框架图示 安装及配置 创建一个Django项目 目录介绍 运行Django项目 启动Django报错 模版文件配置 静态文件配置 A ...
- Django app安装,配置mysql,时区,模板,静态文件,媒体,admin
1.创建app python manage.py startapp 名字 Migrations 数据库同步目录,记录数据库同步的记录 init 包文件 Admin.py django自带的后台管理文件 ...
- Windows下python 3.0版本django的安装、配置、与启动
使用的环境是Windows操作系统,python的环境是3.6,django是官网上最新的版本1.10.6,本文介绍从安装python之后怎样用过pip管理工具安装django,以及django的项目 ...
- Django的安装配置和开发
参考:<Django Web开发指南> Django的安装配置 1.https://www.djangoproject.com/download/下载Django-1.5.1.tar.gz ...
- Ubuntu 16.04 Django安装和配置
之前有安装和配置过,换了台电脑,再安装和配置,忽然发现差不多都忘记了,这里记录下已备之后查阅. sudo apt-get install python-pip sudo apt-get install ...
- Nginx+Python+uwsgi+Django的web开发环境安装及配置
Nginx+Python+uwsgi+Django的web开发环境安装及配置 nginx安装 nginx的安装这里就略过了... python安装 通常系统已经自带了,这里也略过 uwsgi安装 官网 ...
- Django安装和配置环境变量
一.windows系统安装Django 1.先安装python2.x or 3.x软件.(记得勾选pip3和添加python自己的环境变量) 下载地址:http://www.python.org/ 2 ...
- Django中redis的使用方法(包括安装、配置、启动)
一.安装redis: 1.下载: wget http://download.redis.io/releases/redis-3.2.8.tar.gz 2.解压 tar -zxvf redis-3.2. ...
- 基于Ubuntu Server 16.04 LTS版本安装和部署Django之(二):Apache安装和配置
基于Ubuntu Server 16.04 LTS版本安装和部署Django之(一):安装Python3-pip和Django 基于Ubuntu Server 16.04 LTS版本安装和部署Djan ...
- 利用Swoole实现PHP+websocket直播,即使通讯代码,及linux下swoole安装基本配置
swoole安装基本配置 php安装swoole 1. 下载swoole安装 wget http://pecl.php.net/get/swoole-1.9.1.tgz tar -zxvf swool ...
随机推荐
- DB2解锁
1.登录数据库 db2 connect to 数据库名字 user 用户名 using 密码 2.进入db2top db2top -d 数据库名 进入到如下界面: 3.按下shift+u(图中U-L ...
- 《让LoadRunner走下神坛》
这几天碰到这么几件事情,觉得挺有意思的:1. 有个朋友问了我一个问题:LoadRunner的缺点在哪?然后我反问她:LoadRunner的优点在哪?她一时语塞,后来说:感觉都是优点没有什 ...
- python重置变量 sys.defaultencoding
<span style="font-family: Arial, Helvetica, sans-serif;">比如重置变量defaultencoding为utf-8 ...
- BigInteger 与 BigDecimal区别,及BigDecimal详解
一般来说,BigInteger用的不是很多,BigDecimal用的稍微多一点,就比如说JDBC中,如果一个字段的数据库类型是Number, 那么getObject().getClass()的结果是j ...
- Python进行数值计算
1.计算积分 (1)计算定积分 from scipy import integrate #定义函数def half_circle(x): return (1-x**2)**0.5 pi_half, e ...
- Nginx开发从入门到精通 nginx平台初探
初探nginx架构(100%) 众所周知,nginx性能高,而nginx的高性能与其架构是分不开的.那么nginx究竟是怎么样的呢?这一节我们先来初识一下nginx框架吧. nginx在启动后,在un ...
- centos docker
1.安装docker yum install docker --安装docker service docker start --启动docker服务 docker --version --查看版本 ...
- iOS 如何缩小打包项目ipa大小
之前项目上线完全由技术老大搞,这次独立开发自己来,觉得自己的打包项目体积略大,网上搜索了一些比较不错的方法,这里总结下 1.配置编译选项 (Levels选项内)Genetate Debug Symbo ...
- MVVMLight-Mensenger 学习笔记
MVVMLight-Mensenger 最近一直在使用WPF,配合美工很容易能搭配出效果不错的UI来,开发效率也明显加快 自己也是最近才开始使用Mvvmlight,通过view和viewmodel分 ...
- 非常好用的两个PHP函数 serialize()和unserialize()
使用serialize()函数和unserialize()函数,这两个函数的用法真是绝配,一个是进行序列化存储,另一个则是进行序列化恢复,方便极了 今天,在做一个关于PING服务的东西,由于不想把pi ...