在Django中處理WebSockets連接通常需要使用一個庫來處理實時通信,最常見的庫是django_channels。以下是一些簡單的步驟來處理WebSockets連接:
pip install channels
INSTALLED_APPS = [
...
'channels',
]
from channels.generic.websocket import WebsocketConsumer
class MyConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def disconnect(self, close_code):
pass
def receive(self, text_data):
self.send(text_data)
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from myapp.consumers import MyConsumer
application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter([
path('ws/myapp/', MyConsumer),
])
),
})
var socket = new WebSocket('ws://localhost:8000/ws/myapp/');
socket.onmessage = function(e) {
console.log(e.data);
};
socket.send('Hello, server!');
通過這些步驟,您可以在Django中處理WebSockets連接并實現實時通信功能。