程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django configuring websocket

編輯:Python

List of articles

      • channels
      • dwebsocket
        • front end
        • Back end
        • effect
        • Keep typing

There are two ways , One is channels, The other is dwebsocket

channels

dwebsocket

front end

Here's a small problem , I always set it up websocket Links are 127.0.0.1:8000, Then it reports an error and cannot be connected socket, Just know this link is to be able to directly access , and URL equally , It is not used internally by the server IP, So use window.location.host As address

<script type="application/javascript">
//terminal
var socket = new WebSocket("ws://"+window.location.host+"/console/ws_console/");
// Trigger after creating the connection 
socket.onopen = function (event) {

socket.send('balabal');
}
// When websocket Accept the information sent by the server This function will be triggered automatically 
socket.onmessage = function (event){

console.log(' received '+event.data);
}
function sendMessage(){

let tag = document.getElementById("txt");
socket.send(tag.value);
}
function closeConn() {

socket.close(); // The server sends a disconnect request 
}
</script>

Back end

Inside app All are console, It's just a random one app
Install it.

pip3 install dwebsocket

Configure it app

INSTALLED_APPS = [
......
'dwebsocket',
]

Configure the routing urls.py

urlpatterns = [
......
url(r'^ws_console/$',views.wsConsole),
]

Configure view file views.py
Both of the decorators here can be used , But if you use require Words , May affect normal HTTP request

from dwebsocket.decorators import accept_websocket
from dwebsocket import require_websocket
@require_websocket
def wsConsole(request):
if request.is_websocket():
WS=request.websocket
message = WS.wait()
print(message.decode('utf-8'))
WS.send(message)

Several commonly used websocket Method

request.is_websocket(): Determine if the request is websocket The way , Is to return true, Otherwise return to false
request.websocket: When the request is websocket When , Will be in request Add one websocket attribute ,
WebSocket.wait() Return a message sent by the client , Failure to receive a message will result in congestion
WebSocket.read() and wait You can also accept the returned message , But this is non blocking , No message returned None
WebSocket.count_messages() Number of returned messages
WebSocket.has_messages() Return whether there is a new message
WebSocket.send(message) Send messages like clients ,message by byte type

effect

Then enter the page , stay console There will be output in it , At the same time, there will be such an error , It is possible that the above operation is one-off , After the execution, the link is broken
(index):361 WebSocket connection to ‘ws://192.168.1.110:8000/console/ws_console/’ failed: Invalid frame header

Keep typing

If continuous input is required , First, modify the front end , Let's turn it into three buttons first , Connect 、 Send and disconnect . At the same time, the returned content will be displayed in p In the label
The front-end code

// Control 
<div>
<input type="text" placeholder=" Please enter " id="text">
<input type="button" value=" send out " onclick="sendMessage()">
<input type="button" value=" close " onclick="closeSocket()">
<input type="button" value=" link " onclick="connectSocket()">
<p id="result-text">sss</p>
</div>
//script
<script type="application/javascript">
//var socket = new WebSocket("ws://"+window.location.host+"/console/ws_console/");
// Trigger after creating the connection 
function connectSocket(){

if (window.socket){

alert(" Link established ");
return ;
}
var socket = new WebSocket("ws://"+window.location.host+"/console/ws_console/");
socket.onopen = function (event) {

socket.send('balabal');
}
socket.onmessage = function (event){

console.log(' received '+event.data);
}
window.socket=socket;
}
// When websocket Accept the information sent by the server This function will be triggered automatically 
function sendMessage(){

if (!window.socket){

alert(" No connection established , Unable to send ");
}
socket.send($("#text").val());
}
function closeSocket() {

if (window.socket){

window.socket.close();
console.log(" Closed successfully ");
}
}
</script>

Modify the backend views.py Code for
It is equivalent to polling all the time , Receive the content from the front end , As bash Command execution , Return the result , On display in p In the label

import subprocess
@require_websocket
def wsConsole(request):
if request.is_websocket():
for message in request.websocket:
# Judge whether to turn off 
if not message:
print(' Shut down the ')
else:
Command=message.decode('utf-8')
print(Command)
Result=subprocess.getoutput(Command)
request.websocket.send(Result.encode('utf-8'))

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved