Python WebSocket客户端连接但不发送消息

时间:2017-12-19 22:52:14

标签: python django websocket python-multithreading channels

使用websocket客户端将测试消息发送到django服务器时,我无法使用可以发送和接收消息的脚本。

我尝试过以下python脚本:

import websocket
import threading
import json
from time import sleep

# handle message event
def on_message(ws, message):
    print("message recieved: %s" % message)

# handle close event
def on_close(ws):
    print("channel closed")

# execute as main script
if __name__ == "__main__":
    websocket.enableTrace(True)
    # new app object connecting to headstation
    ws = websocket.WebSocketApp("ws://192.168.0.106:8000/?testI123", on_message = on_message, on_close = on_close)
    # run in a new thread - kill if script ends
    ws_listener = threading.Thread(target=ws.run_forever())
    ws_listener.daemon = True
    # start second thread
    ws_listener.start()

    # attempt connection 5 times
    timeout = 5
    while not ws.sock.connected and timeout:
        sleep(1)
        timeout -= 1
    # error on timeout
    if (timeout == 0):
        print("Connection to server timed out") 

    print("test 1")
    # periodically send test message to server
    message_num = 0
    while ws.sock.connected:
        # send node id and message
        message = 'hello %d'%message_num
        ws.send(message)
        sleep(1)
        message_num += 1

此连接成功,由服务器指示,并接收从服务器发送的消息,但不发送任何内容。

终端上会显示类似的内容:

send: b'\x8a\x84\xe2\xe9\xa8\xe2\x8f\xdc\xe2\x84'

如果我只是使用

ws = websocket.WebSocket()
ws.connect(url)
ws.send("hello")

然后这完美。建议上面显示的我的小python脚本有问题。

1 个答案:

答案 0 :(得分:1)

发现问题,当然是愚蠢的错误:

 ws_listener = threading.Thread(target=ws.run_forever())

应该是:

 ws_listener = threading.Thread(target=ws.run_forever)

没有括号。

第一个将ws.run_forever的结果传递给目标,第二个将ws.run_forever设置为目标,这是预期的结果。