Django Websocket通信

时间:2019-01-28 07:02:44

标签: python django websocket django-channels

我有一个Web应用程序,其中我已经使用tutorial实现了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客户端,该客户端使用Web套接字将消息发送到Django Channels应用程序。 A simple python websocket 但我无法连接。

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 :(得分:1)

ws = websocket.WebSocketApp("ws://localhost:8000/power/room/",更改为        ws = websocket.WebSocketApp("ws://localhost:8000/ws/power/room/",