1、安装 dwebsocket
(venv) C:code_objectwebsocketTest>pip install dwebsocket -i https://pypi.douban.com/simple
2、当前项目环境
python版本
1 (venv) C:code_objectwebsocketTest>python --version
2 Python 3.4.4
django版本
1 (venv) C:code_objectwebsocketTest>pip list dwebsocket 2 Django (1.10) 3 dwebsocket (0.5.5) 4 pip (9.0.1) 5 setuptools (28.8.0) 6 six (1.11.0)
3、相关代码
urls.py
1 from django.conf.urls import url, include 2 3 from websocketTest import views 4 urlpatterns = [ 5 url(r'^websocket/', views.websocket_test), 6 url(r'^echo/', views.echo), 7 ]
views.py
1 from dwebsocket import require_websocket,accept_websocket 2 import dwebsocket 3 4 from django.http.response import HttpResponse 5 from django.shortcuts import render 6 import json 7 8 import redis 9 rc = redis.StrictRedis(host='redis_host', port=6379, db=8, decode_responses=True) 10 11 12 @require_websocket # 只接受websocket请求,不接受http请求,这是调用了dwebsocket的装饰器 13 def websocket_test(request): 14 message = request.websocket.wait() 15 request.websocket.send(message) 16 17 18 @accept_websocket # 既能接受http也能接受websocket请求 19 def echo(request): 20 if not request.is_websocket(): 21 try: 22 print('---- request.GET 数据:--->>',request.GET) 23 message = request.GET['message'] 24 return HttpResponse(message) 25 26 except Exception as e: 27 print('---- 报错: e--->>',e) 28 return render(request,'test_websocket/user2.html') 29 30 else: 31 redis_my_key = '' 32 while True: 33 # print(dir(request.websocket)) 34 # print('request.websocket.count_messages() -->', request.websocket.count_messages()) 35 if request.websocket.count_messages() > 0: 36 for message in request.websocket: 37 38 print('request.websocket._get_new_messages() -->', request.websocket._get_new_messages()) 39 if request.websocket.is_closed(): 40 print('连接关闭') 41 return HttpResponse('连接断开') 42 else: 43 44 # print('request.websocket.is_closed() -->', request.websocket.is_closed()) 45 print('--- request.is_websocket() 数据: --->>',message) 46 47 # 将数据写入数据库 {"my_uuid":"1","your_uuid":"2","message":"Hello, World!"} 48 data = json.loads(message.decode()) 49 conn_type = data.get('type') 50 my_uuid = data.get('my_uuid') 51 your_uuid = data.get('your_uuid') 52 msg = data.get('message') 53 redis_my_key = 'message_{uuid}'.format(uuid=my_uuid) 54 redis_you_key = 'message_{uuid}'.format(uuid=your_uuid) 55 56 if conn_type == 'register': 57 if my_uuid and your_uuid: 58 request.websocket.send("注册成功".encode('utf-8')) 59 else: 60 request.websocket.send("uuid为空,链接断开".encode('utf-8')) 61 # request.websocket.close() 62 return HttpResponse('uuid为空,连接断开') 63 elif conn_type == 'sendMsg': 64 rc.lpush(redis_my_key, msg) 65 rc.lpush(redis_you_key, msg) 66 67 break 68 elif redis_my_key: 69 data = rc.rpop(redis_my_key) 70 if data: 71 print('收到消息,立马发送data -->', data) 72 request.websocket.send(data.encode('utf-8')) 73 74 # print(dir(request.websocket)) 75 # request.websocket.send(message + '这是您发来的 @@@ '.encode('utf-8'))
app02/user2.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>django-websocket</title> 5 <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> 6 <script type="text/javascript">//<![CDATA[ 7 $(function () { 8 $('#connect_websocket').click(function () { 9 if (window.s) { 10 window.s.close() 11 } 12 /*创建socket连接*/ 13 var socket = new WebSocket("ws://" + '127.0.0.1:8000' + "/echo/"); 14 socket.onopen = function () { 15 console.log('WebSocket open');//成功连接上Websocket 16 17 const my_uuid=$('#my_uuid').val(); 18 const your_uuid=$('#your_uuid').val(); 19 const sendData = { 20 type: 'register', 21 my_uuid, 22 your_uuid, 23 }; 24 window.s.send(JSON.stringify(sendData)); 25 }; 26 27 socket.onmessage = function (e) { 28 console.log('message: ' + e.data);//打印出服务端返回过来的数据 29 $('#messagecontainer').prepend('<p>' + e.data + '</p>'); 30 }; 31 // Call onopen directly if socket is already open 32 if (socket.readyState == WebSocket.OPEN) socket.onopen(); 33 window.s = socket; 34 }); 35 $('#send_message').click(function () { 36 //如果未连接到websocket 37 if (!window.s) { 38 alert("websocket未连接."); 39 } else { 40 const my_uuid=$('#my_uuid').val(); 41 const your_uuid=$('#your_uuid').val(); 42 const message=$('#message').val(); 43 const sendData = { 44 type: 'sendMsg', 45 my_uuid, 46 your_uuid, 47 message 48 }; 49 window.s.send(JSON.stringify(sendData));//通过websocket发送数据 50 } 51 }); 52 $('#close_websocket').click(function () { 53 if (window.s) { 54 window.s.close();//关闭websocket 55 console.log('websocket已关闭'); 56 } 57 }); 58 59 }); 60 //]]></script> 61 </head> 62 <body> 63 <br> 64 <div> 65 输入自己的ID: <input type="text" id="my_uuid" value=""/> 66 </div> 67 <div> 68 发送给谁的ID: <input type="text" id="your_uuid" value=""/> 69 </div> 70 <input type="text" id="message" value=""/> 71 <button type="button" id="connect_websocket">连接 websocket</button> 72 <button type="button" id="send_message">发送 message</button> 73 <button type="button" id="close_websocket">关闭 websocket</button> 74 <h1>Received Messages</h1> 75 <div id="messagecontainer"> 76 77 </div> 78 </body> 79 </html>