一、创建项目(dj_websocket):
1、创建项目
python django-admin.py startproject dj_websocket
2、进入项目
cd dj_websocket
3、创建APP(myapp)
python manage.py startapp myapp
4、创建,static (静态文件夹),已经 templates(模板文件夹)
mkdir static
mkdir templates
二、配置 settings.py
1、在 INSTALLED_APPS 列表加上(myapp):
INSTALLED_APPS = [
...,
'myapp',
]
2、在 TEMPLATES 列表的DIRS加上:
TEMPLATES = [
{
...,
'DIRS': [os.path.join(BASE_DIR, 'templates')],
...,
},
]
3、在文件末尾加上:
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]
三、views.py 文件编写:
import json
import time
import datetime
from django.shortcuts import render
from dwebsocket.decorators import accept_websocket,require_websocket
# Create your views here.
def index(request):
return render(request, 'index.html',{'init':'init'})
@accept_websocket
def echo(request):
if not request.is_websocket():#判断是不是websocket连接
#如果是普通的http方法
try:
message = request.GET['message']
return HttpResponse(message)
except:
return render(request,'index.html')
else:
# 如果是websocket请求
for message in request.websocket:
request.websocket.send(message)#发送消息到客户端
#request.websocket.send(message)
# 推送10次,当然你可以无限次的推送
for i in range(10):
dt = str(datetime.datetime.now())
s={'test':f"你好 {i} {dt}"}
s=json.dumps(s).encode()
request.websocket.send(s)
time.sleep(0.1) # 间隔0.1秒
四、urls.py 文件编写:
from django.conf.urls import url
from django.contrib import admin
from myapp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', views.index),
url(r'^echo$', views.echo),
]
五、index.html 编写(templates文件夹)
其中使用了 jquery-1.8.3.min.js ,需要下载到我们的 static 文件夹
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>django-websocket</title>
{% load staticfiles %}
<script src="{% static 'jquery-1.8.3.min.js' %}"></script>
<script type="text/javascript">//<![CDATA[
$(function () {
/*创建socket连接
var socket = new WebSocket("ws://" + window.location.host + "/echo");
socket.onopen = function () {
console.log('WebSocket open');//成功连接上Websocket
socket.send($('#message').val());//通过websocket发送数据
};
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();
// 这些代码可以实现一进入页面就自动推送,不可停止
*/
$('#connect_websocket').click(function () {
if (window.s) {
window.s.close();
}
/*创建socket连接*/
var socket = new WebSocket("ws://" + window.location.host + "/echo");
socket.onopen = function () {
console.log('WebSocket open');//成功连接上Websocket
};
socket.onmessage = function (e) {
console.log('message: ' + e.data);//打印出服务端返回过来的数据
var d= $.parseJSON(e.data);
//alert(typeof(d));
$('#messagecontainer').prepend('<p>' + d.test + '</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 {
window.s.send($('#message').val());//通过websocket发送数据
}
});
$('#close_websocket').click(function () {
if (window.s) {
window.s.close();//关闭websocket
console.log('websocket已关闭');
}
});
});
//]]></script>
</head>
<body>
<br>
<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>
{{init}}
</body>
</html>
六、开始执行:
这两句在这里不是必要的
python manage.py makemigrations
python manage.py migrate
运行服务器
python manage.py runserver
七、访问:
打开浏览器输入地址:http://localhost:8000/index/
我们将看到页面:
点击连接,再点击发送,开始推送: