docs: add example with @socket.io/postgres-adapter

[skip ci]
This commit is contained in:
Damien Arrachequesne
2024-07-19 15:20:12 +02:00
parent 8b0a40fd4a
commit 6e9bff4fcf
6 changed files with 128 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
# Example with `@socket.io/postgres-adapter`
**Table of contents**
<!-- TOC -->
* [How to use](#how-to-use)
* [Documentation](#documentation)
<!-- TOC -->
## How to use
```bash
# start the postgres server
$ docker compose up -d
# run the cluster
$ node cluster.js
# run the client
$ node client.js
```
## Documentation
The documentation can be found here: https://socket.io/docs/v4/postgres-adapter/

View File

@@ -0,0 +1,31 @@
import { io } from "socket.io-client";
const CLIENTS_COUNT = 3;
const PORTS = [3000, 3001, 3002];
for (let i = 0; i < CLIENTS_COUNT; i++) {
const socket = io(`ws://localhost:${PORTS[i % 3]}`, {
// transports: ["polling"],
// transports: ["websocket"],
});
socket.on("connect", () => {
console.log(`connected as ${socket.id}`);
});
socket.on("connect_error", () => {
console.log(`connect_error`);
});
socket.on("disconnect", (reason) => {
console.log(`disconnected due to ${reason}`);
});
socket.on("hello", (socketId, pid) => {
console.log(`received "hello" from ${socketId} (process: ${pid})`);
});
setInterval(() => {
socket.emit("hello");
}, 2000);
}

View File

@@ -0,0 +1,13 @@
import cluster from 'node:cluster';
const SERVERS_COUNT = 3;
cluster.setupPrimary({
exec: 'server.js',
});
for (let i = 0; i < SERVERS_COUNT; i++) {
cluster.fork({
PORT: 3000 + i
});
}

View File

@@ -0,0 +1,7 @@
services:
postgres:
image: postgres:14
ports:
- "5432:5432"
environment:
POSTGRES_PASSWORD: "changeit"

View File

@@ -0,0 +1,12 @@
{
"private": true,
"name": "postgres-adapter-example",
"version": "0.0.1",
"type": "module",
"dependencies": {
"@socket.io/postgres-adapter": "^0.4.0",
"pg": "^8.12.0",
"socket.io": "^4.7.5",
"socket.io-client": "^4.7.5"
}
}

View File

@@ -0,0 +1,40 @@
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/postgres-adapter";
import pg from "pg";
import process from "node:process";
const PORT = process.env.PORT || 3000;
const pool = new pg.Pool({
user: "postgres",
host: "localhost",
database: "postgres",
password: "changeit",
port: 5432,
});
await pool.query(`
CREATE TABLE IF NOT EXISTS socket_io_attachments (
id bigserial UNIQUE,
created_at timestamptz DEFAULT NOW(),
payload bytea
);
`);
pool.on("error", (err) => {
console.error("Postgres error", err);
});
const io = new Server({
adapter: createAdapter(pool)
});
io.on("connection", (socket) => {
socket.on("hello", () => {
// send to anyone except the sender
socket.broadcast.emit("hello", socket.id, process.pid);
});
});
io.listen(PORT);
console.log(`server listening on port ${PORT}`);