create a new django project and copy it into the simplest code:
1, urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path("admin/", admin.site.urls),
path("", views.index),
path("echo/", views.echo),
]
2, views.py
import threading
from django.shortcuts import render_to_response
from dwebsocket.decorators import accept_websocket
def index(request):
return render_to_response("index.html", {})
clients = []
@accept_websocket
def echo(request):
if request.is_websocket:
lock = threading.RLock()
try:
lock.acquire()
clients.append(request.websocket)
for message in request.websocket:
if not message:
break
for client in clients:
client.send(message)
finally:
clients.remove(request.websocket)
lock.release()
3, index.html
<!DOCTYPE html>
<html>
<head>
<title>django-websocket</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("-sharpconnect_websocket").click(function () {
if(window.s){
//
window.s.close()
}
var s = new WebSocket("ws://" + window.location.host + "/echo/");
s.onopen = function () {
console.log("WebSocket open");
};
s.onmessage = function (e) {
console.log("message: " + e.data);
$("-sharpmessagecontainer").prepend("" + e.data + "
");
};
s.onclose = function (e) {
console.log("WebSocket close");
};
// s
window.s = s;
});
$("-sharpsend_message").click(function () {
if(!window.s){
alert("Please connect server.");
}else{
window.s.send($("-sharpmessage").val());
}
});
$("-sharpclose_websocket").click(function () {
if(window.s){
window.s.close();
window.s = null;
}
});
});
</script>
</head>
<body>
<input type="text" id="message" value="Hello, World!" />
<button type="button" id="connect_websocket">Connect websocket</button>
<button type="button" id="send_message">Send message</button>
<button type="button" id="close_websocket">Close websocket</button>
<h1>Received Messages</h1>
<div id="messagecontainer"></div>
</body>
</html>
the project runs, connects, and sends messages normally, but when it is closed, the console prints an error: