Added ASGI server for websocket using the sample chat application as starting point
This commit is contained in:
48
booker/mqtt_collector.py
Normal file
48
booker/mqtt_collector.py
Normal 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)
|
||||
|
||||
Reference in New Issue
Block a user