I want to send events (json strings) via websocket to all clients (to all who established connection via websocket). My code:
I think that asgi and routing are ok
asgi.py
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base_app.settings')
django.setup()
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
),
})
routing.py
from api_producer.consumers import EventWebSocket
websocket_urlpatterns = [
url('ws/start/', EventWebSocket.as_asgi()),
]
The problematic point: Some function generates events and I want to send these events to the clients
from api_producer.consumers import EventWebSocket
def event_producer():
my_socket = EventWebSocket()
my_socket.receive("Some_text")
consumers.py
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
class EventWebSocket(WebsocketConsumer):
def connect(self):
self.channel_name = "CHANNEL_1"
print("CALL_ACCEPT")
async_to_sync(self.channel_layer.group_add)("global", self.channel_name)
self.accept()
def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)("global", self.channel_name)
def receive(self, text_data):
print("RRR_ receive ", text_data)
async_to_sync(self.channel_layer.group_send)(
"global",
{
"type": "global.message",
"text": text_data,
},
)
def chat_message(self, event):
print("CHAT_MESSAGE")
self.send(text_data=event["text"])
def global_event(self, event):
print("GLOB_MESSAGE")
self.send(text_data=event["text"])
My actions: 1 Go to websocketKing and send request ws://127.0.0.1:8000/ws/start/. Log output:
WebSocket HANDSHAKING /ws/start/ [127.0.0.1:37194]
WebSocket HANDSHAKING /ws/start/ [127.0.0.1:37194]
CALL_ACCEPT
HTTP POST /api/start_detection/ 200 [0.57, 127.0.0.1:37238] (trigger event_producer)
What is the proper way to send events?
self.accept()in theconnectmethod of your consumer to complete the handshake and complete the connectionEventWebSocketobject and callingreceiveon it like you are inevent_producer. You need to get a channel layer and send a message to a group/channel that all your consumers are members of