Added ASGI server for websocket using the sample chat application as starting point

This commit is contained in:
2022-04-02 19:30:58 +02:00
parent 13cc1c3f57
commit 5cf49b7d47
17 changed files with 209 additions and 14 deletions

48
booker/mqtt_collector.py Normal file
View File

@@ -0,0 +1,48 @@
from channels.generic.websocket import AsyncWebsocketConsumer
import json
'''
class ScannerCollector(WebsocketConsumer):
def connect(self):
self.accept()
def disconnect(self, close_code):
pass
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
self.send(text_data=json.dumps({
'message': message
}))
'''
class ScannerCollector(AsyncWebsocketConsumer):
async def connect(self):
self.group_name = 'scanner'
# join to group
await self.channel_layer.group_add(self.group_name, self.channel_name)
await self.accept()
async def disconnect(self):
# leave group
await self.channel_layer.group_discard(self.group_name, self.channel_name)
async def receive(self, text_data):
print('>>>', text_data)
msg = '{"message":"pong!"}' if text_data == '{"message":"ping"}' else text_data
print('<<<', msg)
await self.channel_layer.group_send(
self.group_name,
{
'type': 'distribute',
'text': msg
}
)
async def distribute(self, event):
valother = event['text']
await self.send(text_data=valother)