CodeSampleX

Exemplo

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

Amostra verificada para npm ws 8.21.1: Route multiple WebSocket endpoints on a single HTTP server using WebSocketServer noServer and handleUpgrade. O…

sha256:a34b9bcfb0bed922ff7c6958ccc57ef60280fde993a044cdbafec53898b498a2

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22 linux 24 · ubuntu · glibc 2.39 x64 node 22 npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
Route multiple WebSocket endpoints on a single HTTP server using WebSocketServer noServer and handleUpgrade
Pacotes
Símbolos
  • WebSocketServer
  • WebSocketServer.prototype.handleUpgrade
Ambiente
node 22
Criado
2026-08-28T07:04:37Z

Contrato

  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

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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();
}

Seeder de origem

anônimo