Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ericls/oak-channels
Trying to make it easier to write real world websocket applications in oak
https://github.com/ericls/oak-channels
deno oak websocket
Last synced: about 1 month ago
JSON representation
Trying to make it easier to write real world websocket applications in oak
- Host: GitHub
- URL: https://github.com/ericls/oak-channels
- Owner: ericls
- Created: 2021-08-28T03:23:18.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2021-09-16T02:15:29.000Z (about 3 years ago)
- Last Synced: 2024-04-16T07:08:25.668Z (7 months ago)
- Topics: deno, oak, websocket
- Language: TypeScript
- Homepage: https://deno.land/x/oak_channels
- Size: 30.3 KB
- Stars: 7
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Introduction
Inspired by django-channels. oak-channels makes it easier to write real world websocket applications.
oak-channels introduces two concepts: `Consumer` and `Layer`.
`Consumer` represents the websocket connection between a client and the server, it maintains a one-to-one relationship between a client and server and provides some helper method to send and receive messages. `Layer` facilitates sending messages across different application processes and allows consumers to join/leave groups and exchange messages within a group, it maintains many-to-many relationships between groups and consumers.
This diagram illustrates their relationships:
Built-in layers:
- InMemory (doesn't work across processes)
- BroadcastChannel (works with deno deploy, not fully tested)
- RedisPubSub# Quick start
The following is a simple example on the usage of oak-channels:
```typescript
import {
Application,
HttpServerStd,
Router,
} from "https://deno.land/x/[email protected]/mod.ts";
import {
BaseConsumer,
InMemoryLayer,
mountConsumer,
} from "https://deno.land/x/oak_channels/mod.ts";const app = new Application({ serverConstructor: HttpServerStd });
const router = new Router();
const layer = new InMemoryLayer();class EchoConsumer extends BaseConsumer {
async onConnect() {
// add this consumer to group "foo"
await this.groupJoin("foo");
// send group message to all consumers in group "foo", including "self"
await this.layer.groupSend("foo", "new user joined");
}// handle group messages
async onGroupMessage(group: string, message: string | Uint8Array) {
this.send(`${group} says ${message}`)
}// handle client messages
async onText(text: string) {
this.send(text);
}
}router.all("/ws", mountConsumer(EchoConsumer, layer));
app.use(router.routes());
await app.listen({ port: 8000 });
```An example with client side code can be found in `examples/example-echo.ts`