Пример PHP кода:
require('vendor/autoload.php');
use WebSocket\Client;
function command($client, $data, $status = null, $timeout = 10) {
$client->text(json_encode($data));
$timestamp = time();
while (true) {
$receive = $client->receive();
try {
$json = json_decode($receive);
$code = isset($json->status[0]) ? $json->status[0] : -1;
if ($code === $status) {
return $json;
}
} catch (Exception $e) {}
if ((time() - $timestamp) > $timeout) {
throw new Exception("WebSocket timeout {$timeout}");
}
}
}
Мой код на Python, не знаю, насколько он аналогичен и как выставить таймаут:
import asyncio
from concurrent.futures import TimeoutError as ConnectionTimeoutError
import json
import websockets
async def command(client, data, status=None):
while True:
await client.send(json.dumps(data))
try:
receive = await client.recv()
code = json.loads(receive)["status"][0]
if code == status:
return receive
except (KeyError, ValueError) as err:
print(f"[error from command()] => {err}")
async def main():
async with websockets.connect("ws://example.com:8005") as client:
while True:
try:
response = await asyncio.wait_for(
command(client, data, status),
timeout=10,
)
print(response)
await asyncio.sleep(1)
except TimeoutError as err:
print(f"[error from main()] => {err}")
P.S. поправил код, посмотрите пожалуйста