WebSocket 快速入门
使用以下地址,将客户端名称替换为你的应用名称:
ws://127.0.0.1:42070/?client=YourAppclient 查询参数是必填项。名称包含空格或特殊字符时请进行 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 示例
Section titled “Python 示例”安装客户端库:
python -m pip install websocket-clientimport jsonfrom 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);示例完成后会断开连接。长期运行的集成可复用连接,并应在连接失败后重新连接。
