CodeSampleX

サンプル

ws 8.21.3: Run a WebSocket server and client round trip with ws

検証済みサンプル — npm ws 8.21.3: Run a WebSocket server and client round trip with ws. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました.

sha256:91b961d23ba84c3205b8885fc80b5203a7d47a923e7a8aab6729d513e2a66a95

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
3
ビルドした署名鍵
3
宣言された環境 node 22 linux x64 node 22 npm

検証実行環境

環境 コントラクト ステージ 実行日
node 22 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-13
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-17
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-09-07

ケース

HOW
ゴール
Run a WebSocket server and client round trip with ws
パッケージ
シンボル
  • WebSocketServer
  • WebSocket
環境
node 22
作成日
2026-08-13T15:20:48Z

コントラクト

  1. start a WebSocketServer on an ephemeral port
  2. connect with a ws client and send a message
  3. assert the server received it and the echoed reply arrived
  4. assert both sides closed cleanly

ファイル

  • csx.json
  • package-lock.json
  • package.json
  • src/index.mjs
  • test/contract.mjs

ソースアーティファクトをダウンロード (tar.gz)

ソース

csx.json
{"case":{"caseId":"case:sha256:b14a37c3af8b097a19b4f33c378c82a108142c346747ca86fcd0104ba361203d","constraints":{"moduleSystem":"esm","runtime":"node"},"contract":["start a WebSocketServer on an ephemeral port","connect with a ws client and send a message","assert the server received it and the echoed reply arrived","assert both sides closed cleanly"],"goal":"Run a WebSocket server and client round trip with ws","kind":"HOW","packages":["pkg:npm/ws@8.21.3"],"schemaVersion":1,"symbols":["WebSocketServer","WebSocket"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","moduleSystem":"esm","os":"linux","packageManager":"npm","runtime":"node","runtimeVersion":"22","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/ws@8.21.3"],"schemaVersion":1,"symbols":["WebSocketServer","WebSocket"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "csx-sample-ws-echo-roundtrip",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "csx-sample-ws-echo-roundtrip",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "ws": "8.21.3"
      }
    },
    "node_modules/ws": {
      "version": "8.21.3",
      "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
      "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
      "license": "MIT",
      "engines": {
        "node": ">=10.0.0"
      },
      "peerDependencies": {
        "bufferutil": "^4.0.1",
        "utf-8-validate": ">=5.0.2"
      },
      "peerDependenciesMeta": {
        "bufferutil": {
          "optional": true
        },
        "utf-8-validate": {
          "optional": true
        }
      }
    }
  }
}
package.json
{
  "name": "csx-sample-ws-echo-roundtrip",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "ws": "8.21.3"
  }
}
src/index.mjs
import { WebSocketServer, WebSocket } from 'ws';

// ws is CommonJS but ships named exports that ESM can import directly.
// Messages arrive as Buffer by default, so compare with String(data) rather
// than === on the raw value.
export function startEchoServer() {
  const server = new WebSocketServer({ port: 0, host: '127.0.0.1' });
  server.on('connection', (socket) => {
    socket.on('message', (data) => socket.send(`echo:${String(data)}`));
  });
  return new Promise((resolve) => server.on('listening', () => resolve(server)));
}

export function askEcho(port, message) {
  return new Promise((resolve, reject) => {
    const client = new WebSocket(`ws://127.0.0.1:${port}`);
    client.on('open', () => client.send(message));
    client.on('message', (data) => {
      client.close();
      resolve(String(data));
    });
    client.on('error', reject);
  });
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import { startEchoServer, askEcho } from '../src/index.mjs';

const server = await startEchoServer();
const { port } = server.address();

const reply = await askEcho(port, 'hello');
assert.equal(reply, 'echo:hello');

await new Promise((r) => server.close(r));
console.log('CONTRACT PASS: ws server and client completed an echo round trip');

オリジンシーダー

anonymous