django+jquery+websocket+dwebsocket实现客户端直接发送消息
Posted xiaochuchun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django+jquery+websocket+dwebsocket实现客户端直接发送消息相关的知识,希望对你有一定的参考价值。
后台代码:
url:::
url(r‘^echo_cc/(?P<userid>[0-9]+)/(?P<sendid>[0-9]+)$‘, views.echo_c, name=‘echo‘)
views代码:::
from django.shortcuts import render
from dwebsocket.decorators import accept_websocket, require_websocket
from django.http import HttpResponse
from collections import defaultdict
# Create your views here.
@require_websocket
def echo_once(request):
message = request.websocket.wait()
request.websocket.send(message)
@accept_websocket
def echo(request):
if not request.is_websocket(): # 判断是不是websocket连接
try: # 如果是普通的http方法
message = request.GET[‘message‘]
return HttpResponse(message)
except:
return render(request, ‘index.html‘)
else:
for message in request.websocket:
print(message)
message = input(‘>>>‘)
request.websocket.send(message) # 发送消息到客户端
allconn = defaultdict(list)#连接池
@accept_websocket
def echo_c(request, userid,sendid):
print(userid,sendid)
allresult = {}
# 获取用户信息
userinfo = request.user
allresult[‘userinfo‘] = userinfo
# 声明全局变量
global allconn
if not request.is_websocket():#判断是不是websocket连接
try:#如果是普通的http方法
message = request.GET[‘message‘]
return HttpResponse(message)
except:
return render(request, ‘myproject/chat.html‘, allresult)
else:
# 将链接(请求?)存入全局字典中
allconn[str(userid)] = request.websocket
# 遍历请求地址中的消息
for message in request.websocket:
# 将信息发至自己的聊天框
# request.websocket.send(message)
# 将信息发至其他所有用户的聊天框
allconn[str(sendid)].send(message)
# for i in allconn:
# if i != str(userid):
# allconn[i].send(message)
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:8080/echo_cc/3/2");/* 前面为自己id,后面为发送id*/----------------------------------------------------------------------》》》这里要改一下,这个是个简单demo
socket.onopen = function () {
console.log(‘WebSocket open‘);//成功连接上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();
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="Hello, World!"/>
<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+jquery+websocket+dwebsocket实现客户端直接发送消息的主要内容,如果未能解决你的问题,请参考以下文章
使用daphne部署django channles websocket 项目
Django、websockets、Tornado,如何让它们通信?