簡體   English   中英

將數據從 Python Web 套接字客戶端發送到 Django 通道

[英]Sending data from Python Web socket client to Django Channels

我正在嘗試從Python 網絡套接字客戶端向 Django 頻道( 聊天應用程序)發送數據。 我能夠進行握手,但我的數據(字符串)未填充到聊天網頁中。

我的 Django 頻道消費者

消費者.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
        }))

我的 Python 網絡套接字客戶端

我的 websocket.py

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

def on_error(ws, error):
    print ("eroror:", 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/ws/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()

我在 ASGI 服務器上收到的錯誤是

WebSocket CONNECT /ws/power/room/ [127.0.0.1:50918]
Exception inside application: Expecting value: line 1 column 1 (char 0)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\sessions.py", line 179, in __call__
    return await self.inner(receive, self.send)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\middleware.py", line 41, in coroutine_call
    await inner_instance(receive, send)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\consumer.py", line 59, in __call__
    [receive, self.channel_receive], self.dispatch
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\utils.py", line 52, in await_many_dispatch
    await dispatch(result)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\asgiref\sync.py", line 108, in __call__
    return await asyncio.wait_for(future, timeout=None)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\asyncio\tasks.py", line 388, in wait_for
    return await fut
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\concurrent\futures\thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\db.py", line 13, in thread_handler
    return super().thread_handler(loop, *args, **kwargs)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\asgiref\sync.py", line 123, in thread_handler
    return self.func(*args, **kwargs)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\consumer.py", line 105, in dispatch
    handler(message)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\generic\websocket.py", line 60, in websocket_receive
    self.receive(text_data=message["text"])
  File "C:\Users\Admin\PycharmProjects\power\myChannels\consumers.py", line 41, in receive
    text_data_json = json.loads(text_data)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
  Expecting value: line 1 column 1 (char 0)
WebSocket DISCONNECT /ws/power/room/ [127.0.0.1:50918] 

我在客戶端收到的錯誤是

WebSocket HANDSHAKING /ws/power/room/ [127.0.0.1:50918]
WebSocket CONNECT /ws/power/room/ [127.0.0.1:50918]
Exception inside application: Expecting value: line 1 column 1 (char 0)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\sessions.py", line 179, in __call__
    return await self.inner(receive, self.send)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\middleware.py", line 41, in coroutine_call
    await inner_instance(receive, send)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\consumer.py", line 59, in __call__
    [receive, self.channel_receive], self.dispatch
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\utils.py", line 52, in await_many_dispatch
    await dispatch(result)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\asgiref\sync.py", line 108, in __call__
    return await asyncio.wait_for(future, timeout=None)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\asyncio\tasks.py", line 388, in wait_for
    return await fut
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\concurrent\futures\thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\db.py", line 13, in thread_handler
    return super().thread_handler(loop, *args, **kwargs)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\asgiref\sync.py", line 123, in thread_handler
    return self.func(*args, **kwargs)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\consumer.py", line 105, in dispatch
    handler(message)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\generic\websocket.py", line 60, in websocket_receive
    self.receive(text_data=message["text"])
  File "C:\Users\Admin\PycharmProjects\power\myChannels\consumers.py", line 41, in receive
    text_data_json = json.loads(text_data)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
  Expecting value: line 1 column 1 (char 0)
WebSocket DISCONNECT /ws/power/room/ [127.0.0.1:50918]

我認為數據類型有問題。 也許我沒有發送 json 並且它正在制造問題。

嘗試發送 JSON 數據而不是字符串。

import json
...
ws.send(json.dumps({
  'message': "Hello %d" % i
}))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM