콘텐츠로 이동

WebSocket 빠른 시작

아래 주소를 쓰되 클라이언트 이름을 앱 이름으로 바꾸세요.

ws://127.0.0.1:42070/?client=YourApp

client 쿼리 매개변수는 필수입니다. 공백이나 특수 문자가 있는 이름은 URL 인코딩하세요.

SendNotification 명령으로 텍스트 메시지를 보내세요. jsonData는 JSON 인코딩 문자열이어야 하며 중첩 객체가 아닙니다.

{
"sender": "YourApp",
"target": "AstralOverlay",
"command": "SendNotification",
"jsonData": "{\"title\":\"Hello from YourApp\",\"content\":\"Your first notification.\",\"sourceApp\":\"YourApp\"}"
}

현재 구현은 command와 jsonData를 읽습니다. sender나 target으로 알림을 라우팅하지 않습니다. 다른 명령은 무시됩니다. 전송 성공은 전달 확인이 아닙니다. target은 선택 사항이며 무시됩니다. 예제에서는 설명용 이름으로 AstralOverlay를 쓰지만 생략해도 됩니다.

클라이언트 라이브러리를 설치하세요.

터미널 창
python -m pip install websocket-client
import json
from websocket import create_connection
payload = {
"title": "Build complete",
"content": "Your project is ready.",
"sourceApp": "BuildHelper",
"timeout": 5.0,
}
message = {
"sender": "BuildHelper",
"target": "AstralOverlay",
"command": "SendNotification",
"jsonData": json.dumps(payload),
}
with create_connection("ws://127.0.0.1:42070/?client=BuildHelper") as connection:
connection.send(json.dumps(message))

최신 .NET 콘솔 앱의 경우:

using System;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using var socket = new ClientWebSocket();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await socket.ConnectAsync(
new Uri("ws://127.0.0.1:42070/?client=BuildHelper"), timeout.Token);
var payload = new {
title = "Build complete",
content = "Your project is ready.",
sourceApp = "BuildHelper",
timeout = 5.0
};
var envelope = new {
sender = "BuildHelper",
target = "AstralOverlay",
command = "SendNotification",
jsonData = JsonSerializer.Serialize(payload)
};
var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(envelope));
await socket.SendAsync(
new ArraySegment<byte>(bytes),
WebSocketMessageType.Text, true, timeout.Token);

예제는 끝나면 연결을 끊습니다. 오래 실행되는 연동은 연결을 재사용할 수 있으며 연결 실패 후에는 재연결해야 합니다.

페이로드 문서와 호환성 제한을 참고하세요.