49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
|
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)
|
||
|
|