python/websocket实现向客户端发送消息,以保持套接字打开



帮助我了解如何正确实现它。底线:客户端是充电站,连接、打开插座、向服务器发送消息并接收响应。服务器-监听端口,查看连接的工作站,接收消息并向其发送响应。问题:当客户端连接并发送标头时,我可以向客户端发送消息。但我需要定期向客户端发送消息,以保持套接字打开,我不知道如何实现这一点。有人能告诉我吗?

样本发送代码:

charge_point_id = path.strip('/')
cp = client_main(charge_point_id, websocket)
logging.info(charge_point_id)
print(charge_point_id)
print(path)
await websocket.send(json.dumps([2,"222", "GetLocalListVersion", {}]))
await cp.start()

从客户端接收消息的示例:

class client_main(cp):
errors = False

if not errors:


@on('BootNotification')
def on_boot_notitication(self,    charge_point_vendor, charge_point_model,charge_point_serial_number,firmware_version, 
meter_type, **kwargs):
return call_result.BootNotificationPayload(
status="Accepted",
current_time=date_str.replace('+00:00','Z'),
interval=60
)

在这种情况下,充电站根据ocpp协议打开连接并保持打开,应该可以以某种方式写入


如何向客户端发送消息?我的例子:

@on('Heartbeat')
def on_getlocallistversion(self):
await self.route_message(json.dumps([2,"222","GetLocalListVersion",{}]))
def on_hearbeat(self):
return call_result.HeartbeatPayload(
current_time=datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')+"Z"
)

我得到一个错误:

等待self.route_message(json.dumps([2;,"GetLocalListVersion";,{}](

这是不可能的。只有当客户端连接时才能发送消息。

最新更新