安装dwebsocket
https://github.com/StanleyLe/Utils/tree/StanleyLe-patch-1
下载到本地 在命令行中切换到压缩到的文件夹执行
python setup.py install
简单使用
<script type="text/javascript">
var socket = new WebSocket("ws:" + window.location.host + "/drug/drug_connect/");
socket.onopen = function () {
console.log('WebSocket open');//成功连接上Websocket
socket.send('adasdasda。。。。');//发送数据到服务端
};
socket.onmessage = function (e) {
console.log('message: ' + e.data);//打印服务端返回的数据
};
socket.onclose=function(e){
console.log(e);
socket.close(); //关闭TCP连接
};
if (socket.readyState == WebSocket.OPEN) socket.onopen();
</sctipt>
drug/urls.py
url(r'drug_connect/$', views.drug_connect, name='drug_connect'),
drug/views.py
from dwebsocket.decorators import accept_websocket
@accept_websocket
def drug_socket(request):
if request.is_websocket():
try:
while 1:
message = request.websocket.wait() # 接受前段发送来的数据
if message:
message = bytes.decode(message)
if message != '886':
try:
receive_data = RFID_cls.getRFID()
if receive_data:
request.websocket.send(receive_data.encode()) # 发送给前段的数据
time.sleep(1)
except Exception as e:
request.websocket.close()
return
else:
print('socket请求关闭!!!')
request.websocket.close()
return
except Exception as e:
try:
request.websocket.close()
return
except:
return