from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
import paramiko
import threading
import time
from channels.layers import get_channel_layer
channel_layer = get_channel_layer()
class MyThread(threading.Thread):
def __init__(self, id, chan):
threading.Thread.__init__(self)
self.chan = chan
def run(self):
while not self.chan.chan.exit_status_ready():
time.sleep(0.1)
try:
data = self.chan.chan.recv(1024)
async_to_sync(self.chan.channel_layer.group_send)(
self.chan.scope['user'].username,
{
"type": "user.message",
"text": bytes.decode(data)
},
)
except Exception as ex:
print(str(ex))
self.chan.sshclient.close()
return False
class EchoConsumer(WebsocketConsumer):
def connect(self):
# 创建channels group, 命名为:用户名,并使用channel_layer写入到redis
async_to_sync(self.channel_layer.group_add)(self.scope['user'].username, self.channel_name)