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 ...
随机推荐
- 使用CAsyncSocket总结
最近想起CAsyncSocket这个类,记得很早以前用过,现在却想不起来怎么用了,翻了翻以前的代码又看了看msdn感觉这个类做简单的异步socket太简单了,几行代码就可以搞定,在此先做个总结. 不管 ...
- MATLAB 的数据类型
在MATLAB中有15种基本的数据类型: 8种整型数据类型.单精度浮点型(float).双精度浮点型(double).逻辑型(logical).字符串型(char).单元数组型(cell).结构体类型 ...
- iOS SDK具体解释之NSCopying协议
原创blog,转载请注明出处 http://blog.csdn.net/hello_hwc?viewmode=contents 欢迎关注我的iOS SDK具体解释专栏 http://blog.csdn ...
- varnish学习笔记
varnish cache是一款开源的高性能的缓存server.和老牌的Squid对照有例如以下长处. 1:varnish是基于内存缓存数据的,所以处理速度比Squid要快. 2:varnish支持更 ...
- 动态设置spring配置PropertyPlaceholderConfigurer location的路径
在spring中经常将常用的属性放在properties文件中,然后再spring的配置文件中使用PropertyPlaceholderConfigurer引用properties文件.对于web项目 ...
- c++ 宏 #val 在unicode下的使用。
#define CHECK(condition) cout<<check failed:<<#condition<<endl; 上面这句宏,当你 CHECK(myf ...
- iOS 学习笔记六 【APP中的文字和APP名字的国际化多语言处理】
今天为新手解决下APP中的文字和APP名字的国际化多语言处理, 不多说了,直接上步骤: 1.打开你的项目,单机project名字,选中project,直接看图吧: 2.创建Localizable.st ...
- Tomcat启动报错:SERVER: Error ListenerStart 排查过程记录
报错的Tomcat截图: 要排查此问题,首先需要调整tomcat的日志级别,调整成通过log4j来记录日志的方式,具体的调整方式: http://tomcat.apache.org/tomcat- ...
- mysql命令 SHOW TABLE STATUS LIKE '%city%'; 查看表的状态可以查看表的创建时间
show status like '%handler_read_key%'; #走索引的命令的数量. #查看存储引擎 mysql> show variables like '%engine%'; ...
- Servlet 环境设置
开发环境是您可以开发.测试.运行 Servlet 的地方. 就像任何其他的 Java 程序,您需要通过使用 Java 编译器 javac 编译 Servlet,在编译 Servlet 应用程序后,将它 ...