# SocketServer

> Documentation for Redweb 0.13.0. Install that exact version when following these examples.

HTTP-upgrade WebSocket server on top of `ws`. Builds and listens on its own HTTP server by default; if you pass a Node `server`, it attaches upgrade handling and leaves `.listen()` to you unless `listen: true` is explicit.

## Explain it like I’m five

SocketServer is a switchboard for persistent conversations. It accepts a WebSocket upgrade, finds the route for that path, and lets that route handle the connection.

## When should I use it?

Choose it for ws:// endpoints or when a reverse proxy already handles TLS and you need one or more independently configured socket routes.

## Follow the example

This API pattern illustrates the named surface; it may require application-owned classes, credentials, or assets. Start from a complete recipe for a runnable application.

```js
const http = require('http')
const { HttpServer, METHODS, SocketServer } = require('redweb')

const httpServer = new HttpServer({
  listen: false,
  publicPaths: ['./public'],
  services: [
    { serviceName: '/health', method: METHODS.GET, function: (req, res) => res.json({ ok: true }) },
  ],
})

const server = http.createServer(httpServer.app)

new SocketServer({
  server,
  routes: [ChatRoute],
})

server.listen(3030)
```

1. The HTTP server is built or reused according to the options.
2. Upgrade requests are matched to routes instead of being sent to every handler.
3. Each route owns its clients, handlers, services, limits, and cleanup lifecycle.

## Options

- port: number (default 3000)
- listen: boolean (default true for owned servers); supplied servers do not listen unless explicitly true
- server: existing http.Server to attach to without double-listening (optional)
- routes: array of SocketRoute subclasses (defaults to a single DefaultRoute at "/")

## Methods and members

### constructor(options)

Creates or reuses an HTTP server, instantiates supplied routes or a DefaultRoute, attaches upgrade handling, and starts listening only when Redweb owns the server or listen is explicitly true.

### addRoute(RouteClass)

Instantiate and register another `SocketRoute` at runtime.

### handleUpgrade(req, socket, head)

Internal: normalises the request path, picks a matching route (or "/"), and forwards the upgrade to that route's server.

### shutdown()

Closes all registered routes and the underlying HTTP server.

## What should I watch for?

When supplying an existing Node server, Redweb does not assume it should call listen. Make listener ownership explicit and shut down in the reverse order of startup.
