Skip to content

Socket.IO

A deep dive into the webapp-socket-io starter: @SocketIOController, event subscriptions with typed arguments, injected Socket, middleware hooks, and where Socket.IO differs from raw WebSockets.

4 min read Source

Source: webapp-socket-io

Structurally this is the WebSockets starter with a different transport decorator. Reading them back to back isolates what belongs to the framework — controller registration, DI, per-connection instantiation — from what belongs to the protocol: handshake, event names, acks, rooms and fallback.

Project layout

src
├─ app.controller.ts                # GET /  → "Hello World!"
├─ app.controller-socket-io.ts      # @SocketIOController
├─ app.module.ts                    # both controllers in one graph
├─ app.service.ts
└─ bootstrap.ts                     # pipeServer + socket.io pipe + pipeSwagger

The pipe

import {pipeServer} from "@typeix/resty";
import {pipeWebSocket as pipeSocketIO} from "@typeix/resty-socket-io";
import {createServer} from "http";

async function bootstrap() {
  const server = createServer();
  await pipeServer(server, AppModule);
  await pipeSocketIO(server, AppModule);
  server.listen(8080);
}

The function is exported as pipeWebSocket from the Socket.IO package, which is why the starter imports it under the name pipeSocketIO — otherwise the two packages would collide, since a single application can pipe both. It still has to run after pipeServer, because it reads the module injector stored there.

The controller

@SocketIOController({
  providers: [],
  middlewares: []
})
export class AppControllerSocketIO implements IAfterConstruct {

  @Inject() logger: Logger;
  @Inject() socket: Socket;
  @Inject() request: IncomingMessage;

  @Subscribe("message")
  onMessage(@Arg() buffer: Buffer) {
    this.logger.debug({message: buffer.toString()}, "MESSAGE SENT");
    this.socket.emit("message", JSON.stringify({
      message: "RECEIVED: " + buffer.toString()
    }));
  }

  afterConstruct(): void {
    this.logger.info({headers: this.request.headers});
  }
}
Piece Meaning
@SocketIOController({...}) class-level config: request-local providers and middlewares
middlewares: [] Express-style middleware run before the connection is accepted
@Subscribe("message") listens on the Socket.IO event named message
@Arg() the event payload, here a Buffer
@Inject() socket the Socket, used to emit back to that client
@Inject() request the handshake request
afterConstruct() once per connection, after DI

The echo is emitted on the same event name rather than as a return value: a Socket.IO handler answers by emitting, not by returning. Compare the raw WebSocket starter, where the reply is socket.send(...).

Raw WebSocket vs Socket.IO

websockets this starter
Decorator @WebSocketController @SocketIOController
Path config socketOptions: {path: "/ws"} package defaults (/socket.io)
Handler args @Arg() buffer, @Arg() isBinary @Arg() buffer
Reply socket.send(string) socket.emit(event, payload)
Client any WebSocket a Socket.IO client
Extras — middleware, rooms, acks, reconnection, fallback transport

Both instantiate the controller per connection and both resolve it through the same injector, so a service injected into a Socket.IO handler is the same instance the HTTP controller receives.

Verifying the connection

Socket.IO speaks Engine.IO before it speaks Socket.IO, so the handshake is a plain HTTP request:

curl 'http://localhost:8080/socket.io/?EIO=4&transport=polling'

A 200 with an Engine.IO session payload means the endpoint is mounted and a client can connect. A 404 means the request was handled by the resty router instead of the Socket.IO layer: the path is wrong, or the request arrived before the socket layer finished attaching. The pipe itself cannot be in the wrong order — calling it before pipeServer throws immediately.

To exercise @Subscribe, use a Socket.IO client:

const {io} = require("socket.io-client");
const socket = io("http://localhost:8080");
socket.on("connect", () => socket.emit("message", "hello"));
socket.on("message", payload => console.log(payload)); // {"message":"RECEIVED: hello"}

Documentation

As with raw WebSockets, pipeSwagger documents only the HTTP surface:

expect(Object.keys(document.paths)).toEqual(["/"]);

@SocketIOController classes are not @Controller, so they never enter the route definitions. The socket endpoint is described in info.description:

info: {
  title: "Socket.io starter",
  version: "1.0.0",
  description: "http health check plus a socket.io endpoint, which listens on the message event and answers with RECEIVED: <payload>"
}

Socket events need their own contract documentation — event names, payload shapes, acks. Do not inflate an OpenAPI document to pretend it covers them.

Tests

File Kind Covers
app.controller.spec.ts unit the HTTP handler
swagger.spec.ts build-time only / is documented

Connection behaviour is verified against a real listener or a client library, for the same reason as in the WebSocket starter: the upgrade path needs a real socket, and FakeServerApi keeps its server instance private.

Pitfalls

  • Import alias matters. Both packages export pipeWebSocket; alias one of them, or importing both in one application will shadow one silently.
  • middlewares run before DI of the handler. They are negotiated per connection, so they are the place for authentication — not a decorator on the subscribe method.
  • emit is fire-and-forget. If the payload must be acknowledged, use an ack callback in the client and an explicit event for the response; a return value is simply ignored.
  • Socket.IO is not a WebSocket path. A plain ws://host/socket.io client will not connect; the Engine.IO handshake comes first.

Next: return to the tutorial overview, or read the package reference for @typeix/resty-socket-io.