Skip to content

Commit de69b6f

Browse files
Update documentation
Add more and more up-to-date documentation.
1 parent 65def73 commit de69b6f

3 files changed

Lines changed: 380 additions & 51 deletions

File tree

README.md

Lines changed: 127 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,149 @@
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 powerful peer-to-peer networking solution 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**: This library is still under development and considered a beta. The library 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.
9+
10+
## Features
11+
12+
- **True Peer-to-Peer (P2P) Networking**
13+
- Direct client-to-client connections without a central game server
14+
- Lower latency for geographically close players
15+
- Reduced server costs and infrastructure complexity
16+
- No need to duplicate game logic between client and server
17+
- Three main advantages:
18+
1. No server costs - there is no server running the game
19+
2. No double implementation - you don't need to write your game logic twice (for the client and the server)
20+
3. Lower latency - when players are living close by, the latency is often much lower than when connected via a server
21+
22+
- **UDP Performance**
23+
- Choice between reliable (TCP) and unreliable (UDP) channels
24+
- Optimized for real-time gaming with minimal latency
25+
- Perfect for fast-paced multiplayer games
26+
- Unlike WebSockets or HTTP (which use TCP), UDP doesn't pause new packets when one packet is slow or dropped
27+
- This is ideal for real-time updates like position data
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('LOBBY-CODE')
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 Implementation](./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+
## Project Status
2486

87+
This library is currently in alpha stage. While it's being actively used in production by some games, the API may change without warning and without bumping the major version. Please contact us if you're planning to use this library in production.
2588

26-
## Setup
89+
### Roadmap
90+
- [x] Basic P2P connectivity
91+
- [x] Lobby system
92+
- [x] Lobby discovery and filtering
93+
- [ ] WebRTC data compression
94+
- [ ] Connection statistics and debugging tools
95+
- [ ] More extensive documentation
96+
- [ ] API stability
2797

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
98+
## Architecture
99+
100+
### Network Stack
34101
```
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>')
102+
Your Game
103+
104+
Netlib API
105+
106+
WebRTC DataChannels
107+
108+
(STUN/TURN if needed)
109+
110+
UDP Transport
39111
```
40-
(any random UUID is a valid game-id, but if your game is hosted at Poki you should use Poki's game-id)
41112

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

140+
## Contributing
44141

45-
## STUN, TURN & Signaling Backend
142+
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).
46143

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.
144+
## License
49145

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

51148
## Main Contributors
52149

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)