Джанго Вебсокет связи - PullRequest
0 голосов
/ 28 января 2019

У меня есть веб-приложение, в котором я реализовал Django Channels 2 с помощью учебника .Чат работает в соответствии с руководством.

consumer.py

class EchoConsumer(WebsocketConsumer):

    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'power_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

        # Receive message from WebSocket

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

        # Receive message from room group

    def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        })) 

routing.py

websocket_urlpatterns = [
    re_path(r'^ws/power/(?P<room_name>[^/]+)/$', consumers.EchoConsumer),
]

Но теперь я хочу реализовать простой Python-клиент, который отправляет сообщения в приложение Django Channels с помощью веб-сокетов. Простой веб-сокет Python , но я не могу подключиться.

my-websocket.py

def on_message(ws, message):
    print (message)

def on_error(ws, error):
    print (error)

def on_close(ws):
    print ("### closed ###")
    # Attemp to reconnect with 2 seconds interval
    time.sleep(2)
    initiate()

def on_open(ws):
    print ("### Initiating new websocket connectipython my-websocket.pyon ###")
    def run(*args):
        for i in range(30000):
            # Sending message with 1 second intervall
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print ("thread terminating...")
    _thread.start_new_thread(run, ())

def initiate():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://localhost:8000/power/room/",
        on_message = on_message,
        on_error = on_error,
        on_close = on_close)
    ws.on_open = on_open

    ws.run_forever()

if __name__ == "__main__":
    initiate()

Ошибка, которую я получаю, указана ниже ошибка

-----------------------
--- response header ---
[WinError 10054] An existing connection was forcibly closed by the remote host
### closed ###
-----------------------
--- response header ---
[WinError 10054] An existing connection was forcibly closed by the remote host
### closed ###
--- request header ---
GET /power/room/ HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:8000
Origin: http://localhost:8000
Sec-WebSocket-Key: uTsGsGA+SVCdCFymJT8/IQ==
Sec-WebSocket-Version: 13

1 Ответ

0 голосов
/ 28 января 2019

изменить ws = websocket.WebSocketApp("ws://localhost:8000/power/room/", на ws = websocket.WebSocketApp("ws://localhost:8000/ws/power/room/",

...