Skip to content

Commit 6c152fd

Browse files
Update documentation (#221)
Add more and more up-to-date documentation.
1 parent 9a1a990 commit 6c152fd

3 files changed

Lines changed: 361 additions & 50 deletions

File tree

README.md

Lines changed: 123 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,145 @@
11
# The Poki Networking Library &nbsp;&nbsp;[<img src="https://img.shields.io/npm/v/@poki/netlib?color=lightgray">](https://www.npmjs.com/package/@poki/netlib)
22

33
<img align="right" src="https://raw.githubusercontent.com/poki/netlib/main/.github/logo.png" width=140>
4-
The Poki Networking Library is a peer-to-peer library for web games, using WebRTC datachannels to provide UDP connections between players directly. Like the Steam Networking Library, but for web.
5-
Netlib tries to make WebRTC as simple to use as the WebSocket interface (for game development).
4+
The Poki Networking Library is a peer-to-peer networking library for web games, leveraging WebRTC datachannels to enable direct UDP connections between players. Think of it as the Steam Networking Library for the web, designed to make WebRTC as simple to use as WebSockets for game development.
5+
6+
<p></p>
7+
8+
> [!WARNING]
9+
> This library is still under development and considered a beta. While it's being actively used in production by some games, the API can change. Make sure to get in touch if you want to go live with this so we can keep you up-to-date about changes.
10+
11+
## Features
12+
13+
- **True Peer-to-Peer (P2P) Networking**
14+
- Direct client-to-client connections without a central game server
15+
- Lower latency for geographically close players
16+
- Reduced server costs and infrastructure complexity
17+
- No need to duplicate game logic between client and server
18+
- Three main advantages:
19+
1. No server costs - there is no server running the game
20+
2. No double implementation - you don't need to write your game logic twice (for the client and the server)
21+
3. Lower latency - when players are living close by, the latency is often much lower than when connected via a server
22+
23+
- **UDP Performance**
24+
- Choice between reliable (TCP) and unreliable (UDP) channels
25+
- Optimized for real-time gaming with minimal latency
26+
- Perfect for fast-paced multiplayer games
27+
- Unlike WebSockets or HTTP (which use TCP), UDP doesn't pause new packets when one packet is slow or dropped
28+
- Includes reliable data channels for critical events like chat messages or NPC spawns
29+
30+
- **Easy to Use**
31+
- Simple WebSocket-like API
32+
- Built-in lobby system with filtering
33+
- Automatic connection management
34+
- Comprehensive TypeScript support
35+
36+
- **Production Ready**
37+
- Fallback to TURN servers when direct P2P fails
38+
- Built-in connection quality monitoring
39+
- Automatic reconnection handling
40+
- Secure by default
41+
42+
## Quick Start
43+
44+
1. Install the package:
45+
```sh
46+
yarn add @poki/netlib
47+
# or
48+
npm install @poki/netlib
49+
```
650

51+
2. Create a network instance:
52+
```js
53+
import { Network } from '@poki/netlib'
54+
const network = new Network('<your-game-id>')
55+
```
756

8-
## Project Status: alpha
57+
3. Create or join a lobby:
58+
```js
59+
// Create a new lobby
60+
network.on('ready', () => {
61+
network.create()
62+
})
63+
64+
// Or join an existing one
65+
network.on('ready', () => {
66+
network.join('ed84')
67+
})
68+
```
969

10-
This library is still under heavy development and considered in alpha. The library API can and will change without warning and without bumping the major version. Make sure to get in touch if you want to go live with this netlib.
70+
4. Start communicating:
71+
```js
72+
// Send messages
73+
network.broadcast('unreliable', { x: 100, y: 200 })
1174

12-
One missing feature that is next on the roadmap is lobby listing and discovery. Currently you can only connect peers by having players share a lobby code externally.
75+
// Receive messages
76+
network.on('message', (peer, channel, data) => {
77+
console.log(`Received from ${peer.id}:`, data)
78+
})
79+
```
1380

14-
## Library main advantages:
81+
For more detailed examples and API documentation:
82+
- [Basic Usage Guide](./docs/basic-usage.md)
83+
- [Example Usage](./example/)
1584

16-
- **peer-to-peer (p2p)**
17-
Clients connected to each other using this netlib will be connected directly without a central server in between (unless using the fallback TURN server). This has three main advantages:
18-
1. No server costs, there is no server running the game.
19-
1. No double implementation of the game. You don't need to write your game logic twice (for the client and the server).
20-
1. When players are living close by the latency is often a lot lower than when connected via a server
21-
- **UDP**
22-
Most web games rely on WebSockets or HTTP for communication which is always a TCP connection, but for realtime multiplayer games the UDP protocol is preferred. The main reason is:
23-
When one packet is slow or dropped UDP doesn't pause new, already received, packets, this is great for things like position updates. The Poki netlib also supplies a reliable data channel useful for chat or npc spawn events.
85+
## Roadmap
2486

87+
- [x] Basic P2P connectivity
88+
- [x] Lobby system
89+
- [x] Lobby discovery and filtering
90+
- [ ] WebRTC data compression
91+
- [ ] Connection statistics and debugging tools
92+
- [ ] More extensive documentation
93+
- [ ] API stability
2594

26-
## Setup
95+
## Architecture
2796

28-
First add [`@poki/netlib`](https://www.npmjs.com/package/@poki/netlib) as a dependency to your project:
29-
```sh
30-
# either using yarn:
31-
yarn add @poki/netlib
32-
# or using npm:
33-
npm i @poki/netlib
97+
### Network Stack
3498
```
35-
Then you can import and create a _Network_ interface:
36-
```js
37-
import { Network } from '@poki/netlib'
38-
const network = new Network('<your-game-id-here>')
99+
Your Game
100+
101+
Netlib API
102+
103+
WebRTC DataChannels
104+
105+
(STUN/TURN if needed)
106+
107+
UDP Transport
39108
```
40-
(any random UUID is a valid game-id, but if your game is hosted at Poki you should use Poki's game-id)
41109

42-
Next up: read the [**basic usage**](./docs/basic-usage.md) guide and make sure to checkout the [**example code**](./example/).
110+
### Infrastructure Components
111+
112+
#### 1. Signaling Server
113+
- Handles initial peer discovery
114+
- Manages lobby creation and joining
115+
- Facilitates WebRTC connection establishment
116+
117+
#### 2. STUN/TURN Servers
118+
- STUN: Helps peers discover their public IP (by default Google STUN servers)
119+
- TURN: Provides fallback relay when direct P2P fails (when using the Poki hosted version, Cloudflare TURN servers are used)
120+
121+
## Self-Hosting
122+
123+
While Poki provides hosted STUN/TURN and signaling services for free, you can also self-host these components:
124+
125+
1. Set up your own signaling server using the provided Docker image
126+
2. Configure your own STUN/TURN servers
127+
3. Initialize the network with custom endpoints:
128+
```js
129+
const network = new Network('<game-id>', {
130+
signalingServer: 'wss://your-server.com',
131+
stunServer: 'stun:your-stun.com:3478',
132+
turnServer: 'turn:your-turn.com:3478'
133+
})
134+
```
43135

136+
## Contributing
44137

45-
## STUN, TURN & Signaling Backend
138+
We welcome contributions! Please see our [Contributing Guide](./.github/CONTRIBUTING.md) for details. This project adheres to the [Poki Vulnerability Disclosure Policy](https://poki.com/en/c/vulnerability-disclosure-policy).
46139

47-
The netlib is a peer-to-peer networking library which means players are connected directly to each other and data send between them is never send to a server.
48-
That said, to setup these connections we need a signaling service. This backend and STUN/TURN servers are hosted by Poki for free. You can however always decide to host the backend yourself.
140+
## License
49141

142+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
50143

51144
## Main Contributors
52145

docs/api-reference.md

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# API Reference
2+
3+
## Network Class
4+
5+
### Constructor
6+
7+
```typescript
8+
new Network(gameId: string, options?: NetworkOptions)
9+
```
10+
11+
#### Parameters
12+
- `gameId`: A unique identifier for your game. Can be a UUID or your Poki game ID.
13+
- `options`: (Optional) Configuration options
14+
```typescript
15+
interface NetworkOptions {
16+
signalingServer?: string; // Custom signaling server URL
17+
stunServer?: string; // Custom STUN server URL
18+
turnServer?: string; // Custom TURN server URL
19+
}
20+
```
21+
22+
### Methods
23+
24+
#### Lobby Management
25+
26+
##### `create(options?: LobbyOptions): Promise<void>`
27+
Creates a new lobby.
28+
```typescript
29+
interface LobbyOptions {
30+
public?: boolean; // Make lobby visible in listings
31+
maxPlayers?: number; // Maximum number of players allowed
32+
password?: string; // Optional password protection
33+
customData?: any; // Custom lobby data
34+
canUpdateBy?: 'anyone' | 'leader' | 'creator'; // Who can update lobby settings
35+
}
36+
```
37+
38+
##### `join(code: string, password?: string): Promise<void>`
39+
Joins an existing lobby.
40+
41+
##### `list(filter?: object): Promise<Lobby[]>`
42+
Lists available lobbies with optional MongoDB-style filtering.
43+
```typescript
44+
interface Lobby {
45+
code: string; // Lobby identifier
46+
playerCount: number; // Current number of players
47+
public: boolean; // Whether lobby is listed
48+
customData: any; // Custom lobby data
49+
createdAt: Date; // Creation timestamp
50+
updatedAt: Date; // Last update timestamp
51+
leader: string; // Current leader's peer ID
52+
canUpdateBy: string; // Who can update settings
53+
creator: string; // Creator's peer ID
54+
hasPassword: boolean; // Password protection status
55+
maxPlayers: number; // Player limit
56+
}
57+
```
58+
59+
#### Communication
60+
61+
##### `send(channel: string, peerId: string, data: any): void`
62+
Sends data to a specific peer.
63+
- `channel`: Either 'reliable' or 'unreliable'
64+
- `peerId`: Target peer's ID
65+
- `data`: Data to send (string, object, or ArrayBuffer)
66+
67+
##### `broadcast(channel: string, data: any): void`
68+
Sends data to all connected peers.
69+
70+
##### `disconnect(): void`
71+
Disconnects from the current lobby and cleans up resources.
72+
73+
### Events
74+
75+
Subscribe to events using `network.on(eventName, callback)`:
76+
77+
#### Connection Events
78+
- `'ready'`: Network is ready to create/join lobbies
79+
- `'error'`: Network error occurred
80+
- `'connected'`: New peer connected
81+
- `'disconnected'`: Peer disconnected
82+
83+
#### Lobby Events
84+
- `'lobby'`: Lobby created/joined
85+
- `'leave'`: Left lobby
86+
- `'update'`: Lobby settings updated
87+
88+
#### Communication Events
89+
- `'message'`: Received data from peer
90+
91+
## Peer Class
92+
93+
```typescript
94+
interface Peer {
95+
id: string; // Unique peer identifier
96+
latency?: {
97+
last: number; // Most recent latency measurement (in ms)
98+
average: number; // Average latency over time
99+
jitter: number; // Variation in latency
100+
max: number; // Maximum observed latency
101+
min: number; // Minimum observed latency
102+
};
103+
}
104+
```

0 commit comments

Comments
 (0)