LambertC
LambertC

Reputation: 21

How to keep my receiver of Heartbeat alive using python-websockets

Although I can receive Heartbeat from server, but my code can not keep receiving information after running 30 seconds.

I have searched websockets FAQ ,some ping pong communication, but I still don't know why this bug occurred.

async with websockets.client.connect(uri,close_timeout = None) as ws:
    await ws.send(data)
    print(data)
    result = await ws.recv()
    #print(result)
    resultdict = json.loads(result)
    keydict = resultdict["Key"]
    mainkey = json.dumps(keydict)
    #mainkey = mainkey.replace('-','')
    mainkey = mainkey.replace('"','')
    print('原始Key = ',mainkey)
    while True:
       hb = await ws.recv()
       print(hb)

and I got this output

{'CMD': 'HeartBeat', 'TYPE': None, 'SendTime': '2019-09-10T03:39:12.64', 'AreaList': None}
{'CMD': 'HeartBeat', 'TYPE': None, 'SendTime': '2019-09-10T03:39:17.65', 'AreaList': None}
{'CMD': 'HeartBeat', 'TYPE': None, 'SendTime': '2019-09-10T03:39:22.67', 'AreaList': None}
{'CMD': 'HeartBeat', 'TYPE': None, 'SendTime': '2019-09-10T03:39:27.67', 'AreaList': None}
{'CMD': 'HeartBeat', 'TYPE': None, 'SendTime': '2019-09-10T03:39:32.69', 'AreaList': None}
{'CMD': 'HeartBeat', 'TYPE': None, 'SendTime': '2019-09-10T03:39:37.70', 'AreaList': None}
{'CMD': 'HeartBeat', 'TYPE': None, 'SendTime': '2019-09-10T03:39:42.72', 'AreaList': None}
{'CMD': 'HeartBeat', 'TYPE': None, 'SendTime': '2019-09-10T03:39:47.73', 'AreaList': None}

Only received 7 messages, and my code is still running but messages are not printed, and crash finally.

Upvotes: 2

Views: 1694

Answers (1)

HR3Edits
HR3Edits

Reputation: 1

you should probably use something like this:

ws = websocket.WebSocketApp(uri, on_message = on_message, on_error = on_error, on_close = on_close)

ws.on_open = self.on_open

ws.run_forever()

def on_message(message):
    print(message)

def on_error(error):
    print(error)

def on_close():
    print("### closed ###")

def on_open(self):
    ws = self.ws
    p = 'ANY KIND OF OPENING YOU NEED'
    p_load = json.loads(p)
    p_json = json.dumps(p_load)
    ws.send(p_json)

In the on message you can receive any messages. The only thing that you probably have to do is send out every x seconds a heartbeat.

Upvotes: -1

Related Questions