# SocketServer

> Documentation for Redweb 0.16.1. 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?

Use defineApp({ sockets: [ChatRoute] }) for normal startup. Use SocketServer directly to attach routed upgrades to a separately owned Node HTTP server.

## 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
import { HttpServer, SocketServer } from 'redweb'
import { ChatRoute } from './ChatRoute.js'

// Advanced: attach to a listener whose lifecycle your application owns.
const http = new HttpServer({ listen: false, publicPaths: [] })
const sockets = new SocketServer({ server: http.server, routes: [ChatRoute] })

http.server.listen(3030)

// At application shutdown, detach sockets before closing their shared listener.
async function shutdown() {
  await sockets.shutdown()
  await http.shutdown()
}
```

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.
