在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连接并实现实时通信功能。