10. 이벤트 스트림 리스너
다음과 연결됩니다. 이벤트 채널 (항구 10020) 시스템 이벤트를 출력하며, 필요에 따라 심각도, 이름 패턴 및 제외 항목에 따라 필터링할 수 있습니다. 읽기 전용 — 세션 프로필이 없으며, 명령이 전송되지 않습니다.
학습 내용:
- 구독하기 이벤트-웹소켓 (항구
10020) 수동적인 관찰자로서 - 다음 내용을 파싱합니다 이벤트 JSON —
level,name,category,data,message - 최소 심각도 기준으로 필터링
- 대치 문자를 사용한 이름 일치 및 제외
- 이 튜토리얼을 다른 튜토리얼과 함께 사용하여 제어 루프의 성능을 평가해 보세요.
진행 절차
- CLI 플래그 구문 분석 (
--level,--name,--exclude,--no-hide-rate,--port). - [링크]
ws://localhost:10020herstellen (der 이벤트 채널) — 순수히 읽기 전용 관찰자이므로 회의 프로필이 전송되지 않습니다. - 수신되는 각 메시지에 대해 이벤트 JSON을 파싱하고 필터를 적용합니다:
- 다음과 같은 경우 기각하십시오.
level최소 중증도 미만인 경우. - Wenn
--name-명시된 항목 중 해당 사항이 없는 경우(다음 중 어느 하나에 해당하지 않는 경우)는 제외하십시오.name혼자서 또는 ~에 대항하여category/name). - 만약 한
--exclude-해당 사항이 있다면, 기각한다.
- 다음과 같은 경우 기각하십시오.
- 중대도, 정식 명칭, 선택적 메시지 및 선택적 항목이 포함된 나머지 사건들
data-적재량 출력.
매개변수
| 깃발 | 표준 | Zweck |
|---|---|---|
--port | 10020 | 이벤트 채널의 포트 |
-l, --level | info | 경증 — 다음 중 하나 info, notice, warning, error, critical, panic |
-n, --name | (keiner) | 해당 패턴에 맞는 이벤트만 표시 (광범위, 반복 가능) |
-x, --exclude | (keiner) | 해당 패턴에 해당하는 이벤트 숨기기 (전역, 반복 가능) |
--no-hide-rate | false | system-rate-report-이벤트 포함 (기본적으로 숨김 — 출력량이 매우 많음) |
터미널에서 원하는 튜토리얼(04-hello-floor, 05-position-control, 06-combined...)을 실행하고, 이벤트 리스너를 다음 코드로 --no-hide-rate 다른 곳에서. 그 사건 system-rate-report 이 값은 장치의 실제 클럭 속도를 나타냅니다. 동일한 튜토리얼의 Python / C++ nlohmann 및 C++ Glaze 버전을 비교해 보면, 약 4 kHz의 제어 루프에서 직렬화 작업량이 어떻게 달라지는지 확인할 수 있습니다.
# Terminal 1 — pick a variant
./04-haply-inverse-hello-floor # C++ nlohmann
./04-haply-inverse-hello-floor-glz # C++ Glaze
python 04-haply-inverse-hello-floor.py # Python
# Terminal 2 — watch the rate
./10-haply-inverse-events --no-hide-rate
읽은 상태 필드
수신되는 모든 메시지는 하나의 개별 이벤트입니다:
level— 중증도(문자열) (info...panic)name— 이벤트 이름 (예:device-connected,system-rate-report)category— 카테고리 (예:device,session,system)message— 선택 사항, 사람이 읽을 수 있는 문자열data— 선택 사항인 중첩된 JSON 페이로드 (형식은 이벤트에 따라 다름)
전체 이벤트 카탈로그: 이벤트 및 모니터링.
보내기 / 받기
패시브 구독 — 오직 recv() 사용되며, 아무것도 반환되지 않습니다. 세 가지 변형 모두 동일한 필터 파이프라인을 구현하며, Inverse API 특유의 주목할 만한 부분은 이벤트 객체의 형태입니다.
- 파이썬
- C++ (nlohmann)
- C++ (Glaze)
async for msg in websocket 이는 순수 수신 루프의 가장 짧은 형태입니다.
async with websockets.connect(uri) as websocket:
async for msg in websocket:
try:
event = json.loads(msg)
except json.JSONDecodeError:
continue
if accept_event(event, min_level_index, name_patterns, exclude_patterns):
print(format_event(event))
libhv-콜백 모델 — onmessage I/O 스레드에서 실행되며, ENTER 키를 누를 때까지 메인 스레드는 차단됩니다. 이벤트는 유형이 지정되지 않은 JSON 데이터로 처리되며, 각 필드는 .value(...) 기본값으로 읽힙니다.
ws.onmessage = [&](const std::string &msg) {
json event;
try { event = json::parse(msg); } catch (...) { return; }
if (accept_event(event, opts.min_level, opts.name_patterns, opts.exclude_patterns))
print_event(event);
};
ws.open("ws://localhost:10020");
while (std::cin.get() != '\n') {} // block main thread
알려진 이벤트 필드들은 유형이 지정된 event_data-구조를 나타냅니다. 이 필드 data 남는 것은 glz::raw_json_view 이를 통해 (이벤트에 따라 달라지는) 임의로 중첩된 페이로드를 전체 스키마를 정의할 필요 없이 변경 없이 전달할 수 있습니다.
// Struct model — known fields typed, nested `data` kept as raw JSON
struct event_data {
std::string level;
std::string name;
std::string category;
std::string message;
glz::raw_json_view data{};
};
// Send / receive
ws.onmessage = [&](const std::string &msg) {
event_data event{};
if (glz::read<glz_settings>(event, msg)) return; // drop malformed
if (accept_event(event, opts.min_level, opts.name_patterns, opts.exclude_patterns))
print_event(event);
};
ws.open("ws://localhost:10020");
while (std::cin.get() != '\n') {} // block main thread
튜토리얼 10도 SDK와 함께 로컬에 설치됩니다. 다음 위치에서 찾을 수 있습니다. tutorials/10-haply-inverse-events/ 서비스의 설치 디렉터리에서.
관련 주제: 이벤트 및 모니터링 · WebSocket 프로토콜