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 安装及配置的更多相关文章

  1. 【Django】安装及配置

    目录 MVC框架与MTV框架 Django的MTV模式 Django框架图示 安装及配置 创建一个Django项目 目录介绍 运行Django项目 启动Django报错 模版文件配置 静态文件配置 A ...

  2. Django app安装,配置mysql,时区,模板,静态文件,媒体,admin

    1.创建app python manage.py startapp 名字 Migrations 数据库同步目录,记录数据库同步的记录 init 包文件 Admin.py django自带的后台管理文件 ...

  3. Windows下python 3.0版本django的安装、配置、与启动

    使用的环境是Windows操作系统,python的环境是3.6,django是官网上最新的版本1.10.6,本文介绍从安装python之后怎样用过pip管理工具安装django,以及django的项目 ...

  4. Django的安装配置和开发

    参考:<Django Web开发指南> Django的安装配置 1.https://www.djangoproject.com/download/下载Django-1.5.1.tar.gz ...

  5. Ubuntu 16.04 Django安装和配置

    之前有安装和配置过,换了台电脑,再安装和配置,忽然发现差不多都忘记了,这里记录下已备之后查阅. sudo apt-get install python-pip sudo apt-get install ...

  6. Nginx+Python+uwsgi+Django的web开发环境安装及配置

    Nginx+Python+uwsgi+Django的web开发环境安装及配置 nginx安装 nginx的安装这里就略过了... python安装 通常系统已经自带了,这里也略过 uwsgi安装 官网 ...

  7. Django安装和配置环境变量

    一.windows系统安装Django 1.先安装python2.x or 3.x软件.(记得勾选pip3和添加python自己的环境变量) 下载地址:http://www.python.org/ 2 ...

  8. Django中redis的使用方法(包括安装、配置、启动)

    一.安装redis: 1.下载: wget http://download.redis.io/releases/redis-3.2.8.tar.gz 2.解压 tar -zxvf redis-3.2. ...

  9. 基于Ubuntu Server 16.04 LTS版本安装和部署Django之(二):Apache安装和配置

    基于Ubuntu Server 16.04 LTS版本安装和部署Django之(一):安装Python3-pip和Django 基于Ubuntu Server 16.04 LTS版本安装和部署Djan ...

  10. 利用Swoole实现PHP+websocket直播,即使通讯代码,及linux下swoole安装基本配置

    swoole安装基本配置 php安装swoole 1. 下载swoole安装 wget http://pecl.php.net/get/swoole-1.9.1.tgz tar -zxvf swool ...

随机推荐

  1. 利用pandas进行数据分析之三:DataFrame与Series基本功能

    未经同意请勿转载http://www.cnblogs.com/smallcrystal/ 前文已经详细介绍DataFrame与Series两种数据结构,下面介绍DataFrame与Series的数据基 ...

  2. Tomcat 服务器只能存有一个正在运行的项目

    即使新建了一个new project (在同一个工作空间),启动Tomcat 还是会出现先前(工程名)一样的问题/异常. [原因]: 在底下Server 那里——Tomcat 7.X 底下会有很多工程 ...

  3. js实现仿购物车加减效果

    代码如下: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <tit ...

  4. shell脚本与mongo交互

    1.mongo提供*.js的方法供linux调用 #!/bin/bash /usr/local/mongodb/bin/mongo hostname/dbname xxx.js xxx.js 内容如下 ...

  5. SQL中的ISNULL函数介绍

    SQL中有多种多样的函数,下面将为您介绍SQL中的ISNULL函数,包括其语法.注释.返回类型等,供您参考,希望对您学习SQL能够有所帮助. ISNULL 使用指定的替换值替换 NULL. 语法ISN ...

  6. js 判断浏览器内核

    function getOs()  {      var OsObject = "";     if(navigator.userAgent.indexOf("MSIE& ...

  7. javacript计时

    简单的计时: var t=setTimeout("alert('5 秒!')",5000) 无限计时: var c=0 var t function timedCount() { ...

  8. 给linux操作系统安装中文环境

    如果设置的默认环境是英文,需要安装中文环境.最简答的方法如下: sudo apt-get install language-pack-zh-hant sudo apt-get install lang ...

  9. tomcat本身的lib目录都有哪些jar包

    1.tomcat下的lib目录,自己带有的jar包有:servlet.jar,tomcat-jdbc.jar,tomncat-dbcp.jar,jsp.jar等 2.tomcat下的lib目录,自己带 ...

  10. python urllib 和 urllib2

    urllib 和 urllib2 都是接受URL请求的相关模块,但是提供了不同的功能.两个最显著的不同如下: urllib 仅可以接受URL,不能创建 设置了headers 的Request 类实例: ...