Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

16 Commits

Folders and files

Repository files navigation

roomsocket

WebSockets with rooms for shelf, and a client that reconnects on its own

Dart 3.0+ Client: VM, Flutter, Web

  • 🏠 Put clients into rooms and broadcast to a room with one call
  • 🔐 Reject connections before the upgrade, and keep data like the user id on each client
  • 🔁 The client reconnects, queues messages while offline and fetches fresh headers before every connect
  • 🌐 Works in the browser too: a short-lived token from dart_auth travels as ?token=
  • 🔒 Closes connections whose user was signed out, on a timer or right away
  • 💓 Heartbeat on both ends: the server drops clients that stop answering, the client reconnects when the server goes quiet
  • 💤 Pause and resume for apps that go to the background
flowchart LR
    A["📱 Flutter app"] -- WebSocket --> S
    B["🌐 Browser"] -- "WebSocket + ?token=" --> S
    S["RoomSocketShelfAdapter<br/>authenticator"] --> R["RoomSocketServer"]
    R --> L(["room: lobby"])
    R --> M(["room: match-42"])
Loading

Quick start

dependencies:
  roomsocket:
    git:
      url: https://github.com/PyFlat/Roomsocket.git
      ref: main

Server

final sockets = RoomSocketServer();

sockets.onConnect = (client) => sockets.addToRoom('lobby', client);

sockets.onMessage = (client, data) {
  final message = jsonDecode(data as String);
  sockets.broadcast('lobby', {'from': client.payload, 'text': message['text']});
};

final adapter = RoomSocketShelfAdapter(
  sockets,
  authenticator: (request) => isValid(request) ? null : Response.forbidden('Unauthorized'),
  extractRequestData: (request) => userIdFrom(request),
);

await io.serve(Cascade().add(adapter.handler).add(api.call).handler, 'localhost', 8080);

Clients connect to /ws. Every other path gets a 404, so the adapter sits in a Cascade in front of your API.

Client

final socket = RoomSocketClient(
  Uri.parse('wss://example.com/ws'),
  headerProvider: () async => {'authorization': 'Bearer ${await auth.accessToken()}'},
);

socket.listen((data) => print('Received: $data'));
await socket.connect();

socket.send(jsonEncode({'text': 'Hello'}));

In the browser

Browsers can't send headers with a WebSocket. Without queryTokenProvider, the client puts the bearer token from the headers into ?token=, so the access token lands in URLs and logs. Better fetch a short-lived token for every connect, with dart_auth from POST /url-token, and accept it on the server with authMiddleware(allowUrlToken: true):

final socket = RoomSocketClient(
  Uri.parse('wss://example.com/ws'),
  headerProvider: () async => {'authorization': 'Bearer ${await auth.accessToken()}'},
  queryTokenProvider: kIsWeb ? () => api.urlToken() : null,
);

A connection stays open after the user signs out. Let the server check it now and then, or close it right away:

final server = RoomSocketServer(
  revalidate: (client) => auth.isCurrent(client.payload as JwtData),
);

server.closeWhere((client) => (client.payload as JwtData).id == userId);

Reference

Server API
addToRoom(room, client) / removeFromRoom(room, client) Join and leave rooms, clients leave all rooms on disconnect
broadcast(room, value) Sends a JSON-encodable value to everyone in the room
send(client, value) Sends a JSON-encodable value to one client
clients All connected clients
closeWhere(test) Closes every client the test matches, returns how many
client.id / client.payload A generated id and whatever extractRequestData returned
onConnect / onDisconnect / onMessage Hooks, onMessage gets the raw string

RoomSocketServer takes heartbeatInterval (10 seconds) and disconnectDuration (30 seconds): it pings every client at that interval and closes a client that sends no pong within disconnectDuration. With revalidate, it checks every client each revalidateInterval (1 minute) and closes those it returns false for. If it throws, the client stays.

RoomSocketShelfAdapter takes a path (default ws), an authenticator that returns null to accept or a Response to reject, extractRequestData and a custom notFoundResponse.

Client API
connect() / close() Start and stop for good
reconnect(uri:) Connect again right away, optionally to a new address
pause() / resume() Disconnect without reconnecting, for example while the app is in the background
send(message) Sends the message as is, queued while offline
listen(onData, onDone:, onError:) Raw incoming messages, works before connect() too
isConnected / isPaused Current state

Options: headers or headerProvider, queryTokenProvider (called before every connect, its token goes into ?token=, a failure counts as a failed connect), onConnect, onReconnectFailed, reconnectInterval (5 seconds), timeoutDuration (10 seconds) and pingTimeout (30 seconds). Without any message from the server for pingTimeout, the client treats the connection as dead: onError gets a TimeoutException, onDone runs and it reconnects. Pass null to turn this off.

Message format

Messages are JSON strings. The server encodes values for you, the client sends exactly what you pass, so encode it yourself. {"type": "ping"} and {"type": "pong"} belong to the heartbeat and never reach your handlers.

Runnable examples are in example/.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages