CodeSampleX

サンプル

ws 8.21.1: Route multiple WebSocket endpoints on a single HTTP server using WebSocketServer noServer and handleUpgrade

検証済みサンプル — npm ws 8.21.1: Route multiple WebSocket endpoints on a single HTTP server using WebSocketServer noServer and handleUpgrade. node 22 · linux…

sha256:a34b9bcfb0bed922ff7c6958ccc57ef60280fde993a044cdbafec53898b498a2

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

実行証拠

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

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

検証実行環境

環境 コントラクト ステージ 実行日
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-08-28

ケース

HOW
ゴール
Route multiple WebSocket endpoints on a single HTTP server using WebSocketServer noServer and handleUpgrade
パッケージ
シンボル
  • WebSocketServer
  • WebSocketServer.prototype.handleUpgrade
環境
node 22
作成日
2026-08-28T07:04:37Z

コントラクト

  1. create WebSocketServer instances with noServer: true for multiple routes
  2. route incoming HTTP upgrade requests to matching WebSocketServer instances via handleUpgrade
  3. reject upgrade requests for unhandled paths with HTTP 404 and destroy socket
  4. verify separate message handling for /chat and /feed routes
  5. close HTTP and WebSocket servers cleanly

ファイル

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

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

ソース

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: Route multiple WebSocket endpoints on a single HTTP server using WebSocketServer noServer and handleUpgrade
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/ws@8.21.1
Demonstrate these symbols/APIs:
  - WebSocketServer
  - WebSocketServer.prototype.handleUpgrade

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:8858b5f1481b7f56604000eedc37240493771ec9dd866d0d19ffe347bcf8fd14","contract":["create WebSocketServer instances with noServer: true for multiple routes","route incoming HTTP upgrade requests to matching WebSocketServer instances via handleUpgrade","reject upgrade requests for unhandled paths with HTTP 404 and destroy socket","verify separate message handling for /chat and /feed routes","close HTTP and WebSocket servers cleanly"],"goal":"Route multiple WebSocket endpoints on a single HTTP server using WebSocketServer noServer and handleUpgrade","kind":"HOW","packages":["pkg:npm/ws@8.21.1"],"schemaVersion":1,"symbols":["WebSocketServer","WebSocketServer.prototype.handleUpgrade"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","runtime":"node","runtimeVersion":"22","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/ws@8.21.1"],"schemaVersion":1,"subject":"pkg:npm/ws@8.21.1","symbols":["WebSocketServer","WebSocketServer.prototype.handleUpgrade"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "csx-sample-ws-multi-route-handle-upgrade",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "csx-sample-ws-multi-route-handle-upgrade",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "ws": "8.21.1"
      }
    },
    "node_modules/ws": {
      "version": "8.21.1",
      "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz",
      "integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==",
      "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-multi-route-handle-upgrade",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "ws": "8.21.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Route multiple WebSocket endpoints on a single HTTP server using WebSocketServer noServer and handleUpgrade",
  "kind": "HOW",
  "packages": [
    "pkg:npm/ws@8.21.1"
  ],
  "symbols": [
    "WebSocketServer",
    "WebSocketServer.prototype.handleUpgrade"
  ]
}
src/index.mjs
import http from 'node:http';
import { WebSocketServer } from 'ws';

export function createMultiRouteServer() {
  const httpServer = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('HTTP server running');
  });

  const chatWss = new WebSocketServer({ noServer: true });
  const feedWss = new WebSocketServer({ noServer: true });

  chatWss.on('connection', (ws) => {
    ws.on('message', (message) => {
      ws.send(`chat:${String(message)}`);
    });
  });

  feedWss.on('connection', (ws) => {
    ws.on('message', (message) => {
      ws.send(`feed:${String(message)}`);
    });
  });

  httpServer.on('upgrade', (request, socket, head) => {
    const { pathname } = new URL(request.url, 'http://127.0.0.1');

    if (pathname === '/chat') {
      chatWss.handleUpgrade(request, socket, head, (ws) => {
        chatWss.emit('connection', ws, request);
      });
    } else if (pathname === '/feed') {
      feedWss.handleUpgrade(request, socket, head, (ws) => {
        feedWss.emit('connection', ws, request);
      });
    } else {
      socket.write('HTTP/1.1 404 Not Found\r\n\r\n');
      socket.destroy();
    }
  });

  return new Promise((resolve) => {
    httpServer.listen(0, '127.0.0.1', () => {
      const { port } = httpServer.address();
      resolve({
        port,
        httpServer,
        chatWss,
        feedWss,
        close: () =>
          new Promise((done) => {
            chatWss.close();
            feedWss.close();
            httpServer.close(done);
          })
      });
    });
  });
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import { WebSocket } from 'ws';
import { createMultiRouteServer } from '../src/index.mjs';

function communicate(url, payload) {
  return new Promise((resolve, reject) => {
    const ws = new WebSocket(url);
    ws.on('open', () => {
      ws.send(payload);
    });
    ws.on('message', (data) => {
      ws.close();
      resolve(String(data));
    });
    ws.on('error', (err) => {
      reject(err);
    });
  });
}

function expectUpgradeRejection(url) {
  return new Promise((resolve, reject) => {
    const ws = new WebSocket(url);
    ws.on('open', () => {
      ws.close();
      reject(new Error(`Expected upgrade rejection for ${url}, but connection succeeded.`));
    });
    ws.on('error', (err) => {
      // Rejection should cause error event on client
      resolve(err);
    });
  });
}

const server = await createMultiRouteServer();
const { port } = server;

try {
  // Test /chat endpoint
  const chatResponse = await communicate(`ws://127.0.0.1:${port}/chat`, 'hello chat');
  assert.equal(chatResponse, 'chat:hello chat');

  // Test /feed endpoint
  const feedResponse = await communicate(`ws://127.0.0.1:${port}/feed`, 'news item');
  assert.equal(feedResponse, 'feed:news item');

  // Test unhandled route rejection
  const rejectionError = await expectUpgradeRejection(`ws://127.0.0.1:${port}/invalid-route`);
  assert.ok(rejectionError instanceof Error);
  assert.match(rejectionError.message, /404|closed|unexpected/i);

  console.log('CONTRACT PASS: WebSocketServer handleUpgrade routes and rejections verified');
} finally {
  await server.close();
}

オリジンシーダー

匿名