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 ...
随机推荐
- TCP和UDP比較
一.TCP/IP协议 TCP/IP协议,你一定常常听说吧,当中TCP(Transmission Control Protocol)称为传输控制协议,IP(Internet Protocol)称为因特网 ...
- SHOW CREATE DATABASE Syntax
SHOW CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name Shows the CREATE DATABASE statement that cre ...
- shell脚本循环嵌套
嵌套循环 在循环语句内使用任意类型的命令,包括其他循环命令,叫做嵌套循环.因为是在迭代中迭代,需要注意变量的使用以及程序的效率问题. 下面举一个for循环嵌套for循环的例子: wangsx@SC-2 ...
- 预装WIN8改装WIN7之BIOS设置
不少预装WIN8/10的朋友觉得WIN8/10不好用,想改装WIN7,可改装之后常常出现各种问题,甚至不能启动,往往是BIOS设置不当. 本文以联想小新V2000 预装WIN8.1中文版为例,说说WI ...
- c++opencv项目移植到Android(Mat—》IplImage*)
近期将PC机上的行人检測的C++项目移植到Android平台遇到非常多的问题.因此,记录一些重点. 1. 最好能够參照Opencv sample 里面的mix-processing. 2. 数据结构的 ...
- caffe 中如何打乱训练数据
第一: 可以选择在将数据转换成lmdb格式时进行打乱: 设置参数--shuffle=1:(表示打乱训练数据) 默认为0,表示忽略,不打乱. 打乱的目的有两个:防止出现过分有规律的数据,导致过拟合或者不 ...
- [转]实用教程:搭建FTP服务器以实现局域网飞速传输文件
原文地址:https://www.ithome.com/html/win10/304059.htm 相信很多人都面临过这样的问题:一个局域网下有很多设备,我们想在这些设备之间互传文件,有些文件非常大, ...
- js实现div闪烁-------Day46
近期在学着用easyui,发现框架用起来果然是方便简洁,能弄出这框架的都是大神级别了吧,牛啊.... 今天碰到这个应用能够说是让我很之无语,整出源代码来一看就明确了.可之前却还是感觉很奇妙,我也经常告 ...
- docker的使用01
使用Dockerfile构建镜像 vim dockerfile01 #注释信息 FROM ubuntu:latest //导入镜像 MAINTAINER leo "leo@leo.com&q ...
- python统计订单走势
#coding=utf-8 import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotl ...