xiaohongshu
xiaohongshu
72-network-ws-client
Status: ACTIVE AppliesTo: v10 Type: Policy / Requirements
Full skill instructions
Status: ACTIVE
AppliesTo: v10
Type: Policy / Requirements
Devian 런타임에 WebSocket 기반 클라이언트 런타임을 추가한다.
이 SKILL은 정책/요구사항/설계 의도를 정의한다. 구현 및 공개 API는 코드가 정답이며, 여기의 시그니처/예시는 참고용이다.
Namespace 정책: 모든 타입은
namespace Devian단일을 사용한다. 네트워크 계열 public API는Net접두사로 명확화한다.
NetWsClient: WebSocket 클라이언트 (sync public API)
Tick() 기반 폴링NetClient: 프레임 수신 → 디스패치 라우팅INetRuntime: opcode 기반 디스패치 인터페이스 (이미 Net 포함, 유지)NetFrameV1: 프레임 포맷 파서 ([opcode:int32LE][payload...])INetPacketSender, NetPacketEnvelope API 변경 없음이 SKILL은 namespace Devian에 네트워크 기능을 제공한다.
| 기존 | 추가 (이 SKILL) |
|---|---|
INetPacketSender | 변경 없음 |
NetPacketEnvelope | 변경 없음 |
| - | NetFrameV1 |
| - | INetRuntime |
| - | NetClient |
| - | NetWsClient |
framework-cs/module/Devian/src/Net/
├── NetFrameV1.cs
├── INetRuntime.cs
├── NetClient.cs
└── Transports/
└── NetWsClient.cs
Note: 아래는 이해를 돕기 위한 참고 예시이며, 최종 시그니처/공개 API는 코드가 정답이다.
코드 변경 시 이 문서를 'SSOT'로 맞추지 않는다. 필요하면 문서를 참고 수준으로 갱신한다.
namespace Devian
{
public static class NetFrameV1
{
/// <summary>
/// Frame format: [opcode:int32LE][payload...]
/// </summary>
public static bool TryParse(
ReadOnlySpan<byte> frame,
out int opcode,
out ReadOnlySpan<byte> payload);
/// <summary>
/// Build frame into destination buffer.
/// Returns bytes written.
/// </summary>
public static int Build(
Span<byte> destination,
int opcode,
ReadOnlySpan<byte> payload);
/// <summary>
/// Calculate total frame size.
/// </summary>
public static int CalculateSize(int payloadLength);
}
}
namespace Devian
{
public interface INetRuntime
{
/// <summary>
/// Dispatch inbound message by opcode.
/// Returns true if handled, false otherwise.
/// </summary>
bool TryDispatchInbound(int sessionId, int opcode, ReadOnlySpan<byte> payload);
}
}
namespace Devian
{
public sealed class NetClient
{
public NetClient(INetRuntime runtime);
/// <summary>
/// Called by transport when a complete frame is received.
/// Parses frame and dispatches to runtime.
/// </summary>
public void OnFrame(int sessionId, ReadOnlySpan<byte> frame);
}
}
namespace Devian
{
public sealed class NetWsClient : IDisposable
{
public NetWsClient(NetClient core, int sessionId = 0);
public bool IsOpen { get; }
public event Action? OnOpen;
public event Action<ushort, string>? OnClose;
public event Action<Exception>? OnError;
/// <summary>
/// Synchronously connect and start background recv/send threads.
/// </summary>
public void Connect(string url, string[]? subProtocols = null);
/// <summary>
/// Synchronously enqueue frame for sending.
/// </summary>
public void SendFrame(ReadOnlySpan<byte> frame);
/// <summary>
/// Request graceful close.
/// </summary>
public void Close();
/// <summary>
/// Process dispatch queue on calling thread (Unity main thread).
/// WebGL에서는 WS_PollEvent drain도 수행한다.
///
/// 문서 표준 호출명: Tick()
/// Update()는 alias로 유지 (레거시, Unity MonoBehaviour.Update 혼동 방지)
/// </summary>
public void Tick();
/// <summary>
/// Alias for Tick(). 레거시 호환용, 사용 비권장.
/// Unity MonoBehaviour.Update()와 혼동 금지.
/// </summary>
[Obsolete("Use Tick() instead")]
public void Update();
public void Dispose();
}
}
+------------------+------------------+
| opcode (4 bytes) | payload (N bytes)|
| int32 LE | raw bytes |
+------------------+------------------+
로컬 Close() 호출 시 OnClose 이벤트가 반드시 발생해야 한다.
위반 시 FAIL:
ToArray() 호출 금지ArrayPool<byte>.Shared.Rent() → 누적 → 처리 후 재사용Return()SendFrame()은 즉시 반환, 실제 전송은 send threadEndOfMessage에서만 core로 전달WebGL Note: 이 문서에서 "send/recv thread"는 Non-WebGL을 의미한다. WebGL에서는 스레드가 없으며, 수신은 콜백 전달이 아니라 폴링 전달로 수행된다. ToArray 금지, ArrayPool 재사용, 핫 경로 alloc 금지는 동일하게 적용된다. ptr/len free 규칙은 77-webgl-jslib-memory-rules에 위임한다.
async 노출 금지 (Connect, SendFrame, Close는 sync)┌─────────────────┐
│ Main Thread │
│ (Unity Update) │
│ │
│ Tick() ────────┼──→ dispatch queue drain + (WebGL: WS_PollEvent drain)
│ SendFrame() ───┼──→ send queue enqueue
│ Connect() │
│ Close() │
└─────────────────┘
│
▼ (Non-WebGL only)
┌─────────────────┐ ┌─────────────────┐
│ Send Thread │ │ Recv Thread │
│ │ │ │
│ dequeue ───────┼──→ │ ReceiveAsync │
│ SendAsync │ │ ──→ OnFrame() │
└─────────────────┘ └─────────────────┘
Tick() vs Update() 표준화:
Tick()= dispatch queue drain + (WebGL이면 WS_PollEvent drain)Update()=Tick()alias (레거시, Unity MonoBehaviour.Update 혼동 방지 목적상 사용 비권장)
UNITY_WEBGL && !UNITY_EDITOR)WebGL에서는 브라우저 제약으로 스레드 기반 send/recv 루프를 사용하지 않는다.
폴링 기반 모델 (콜백/SendMessage 금지):
.jslib가 이벤트 큐를 유지Tick()에서 WS_PollEvent를 최대 N개까지 drain하여:
OPEN/CLOSE/ERROR → 내부 dispatch queue에 enqueueMESSAGE(ptr, len) → Marshal.Copy → core.OnFrame(sessionId, frame)ArrayPool<byte> + GCHandle.Alloc(Pinned) → WS_SendBinary(ptr,len) (ToArray 없음).jslib가 _malloc으로 WASM heap에 복사 → C#이 Marshal.Copy로 ArrayPool<byte>에 복사 후 처리 → WS_FreeBuffer(ptr)로 해제메모리 규칙:
계약 정본:
| Event | Parameters | 설명 |
|---|---|---|
OnOpen | - | 연결 성공 |
OnClose | ushort code, string reason | 연결 종료 |
OnError | Exception ex | 오류 발생 |
Tick()에서 실행 (Unity 호환)Update()는 Tick() alias (레거시 호환)netstandard2.1 유지ClientWebSocket이 누락되면 System.Net.WebSockets.Client 패키지 조건부 추가 가능Devian (단일 런타임 모듈, namespace Devian)skills/devian-core/10-core-runtime/SKILL.mdxiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience