0
# Socket Connection
1
2
Core Socket functionality for establishing and managing WebSocket connections to Phoenix applications, including connection lifecycle, authentication, and transport configuration.
3
4
## Capabilities
5
6
### Socket Constructor
7
8
Creates a new Phoenix Socket instance with endpoint and configuration options.
9
10
```typescript { .api }
11
/**
12
* Creates a new Phoenix Socket instance
13
* @param endPoint - WebSocket endpoint URL (e.g., "/socket" or "ws://localhost:4000/socket")
14
* @param opts - Socket configuration options
15
*/
16
constructor(endPoint: string, opts?: Partial<SocketConnectOption>);
17
18
interface SocketConnectOption {
19
/** WebSocket binary data type */
20
binaryType: BinaryType;
21
/** Connection parameters (static object or dynamic function) */
22
params: object | (() => object);
23
/** WebSocket transport constructor */
24
transport: new(endpoint: string) => object;
25
/** Default timeout for operations in milliseconds */
26
timeout: number;
27
/** Heartbeat interval in milliseconds */
28
heartbeatIntervalMs: number;
29
/** Milliseconds before falling back to long polling */
30
longPollFallbackMs: number;
31
/** Long polling timeout in milliseconds */
32
longpollerTimeout: number;
33
/** Message encoding function */
34
encode: (payload: object, callback: (encoded: any) => void | Promise<void>) => void;
35
/** Message decoding function */
36
decode: (payload: string, callback: (decoded: any) => void | Promise<void>) => void;
37
/** Logging function for debug output */
38
logger: (kind: string, message: string, data: any) => void;
39
/** Reconnection backoff calculation function */
40
reconnectAfterMs: (tries: number) => number;
41
/** Channel rejoin backoff calculation function */
42
rejoinAfterMs: (tries: number) => number;
43
/** Protocol version string */
44
vsn: string;
45
/** Enable debug logging */
46
debug: boolean;
47
/** Session storage implementation */
48
sessionStorage: object;
49
}
50
51
type BinaryType = "arraybuffer" | "blob";
52
```
53
54
**Usage Example:**
55
56
```typescript
57
import { Socket } from "phoenix";
58
59
// Basic socket connection
60
const socket = new Socket("/socket", {
61
params: { userToken: "abc123" },
62
heartbeatIntervalMs: 30000,
63
debug: true
64
});
65
66
// Advanced configuration with custom transport
67
const advancedSocket = new Socket("/socket", {
68
params: () => ({ token: getAuthToken() }), // Dynamic params
69
reconnectAfterMs: (tries) => [1000, 2000, 5000][tries - 1] || 10000,
70
rejoinAfterMs: (tries) => [500, 1000, 2000][tries - 1] || 5000,
71
logger: (kind, msg, data) => console.log(`Phoenix ${kind}:`, msg, data),
72
binaryType: "arraybuffer",
73
vsn: "2.0.0"
74
});
75
```
76
77
### Connection Management
78
79
Connect, disconnect, and monitor connection state.
80
81
```typescript { .api }
82
/**
83
* Establish WebSocket connection
84
* @param params - Optional connection parameters (overrides constructor params)
85
*/
86
connect(params?: any): void;
87
88
/**
89
* Close WebSocket connection
90
* @param callback - Optional callback to execute after disconnect
91
* @param code - WebSocket close code
92
* @param reason - Reason for disconnection
93
*/
94
disconnect(callback?: () => void | Promise<void>, code?: number, reason?: string): void;
95
96
/**
97
* Get current connection state
98
* @returns Current ConnectionState
99
*/
100
connectionState(): ConnectionState;
101
102
/**
103
* Check if socket is currently connected
104
* @returns True if connected, false otherwise
105
*/
106
isConnected(): boolean;
107
108
type ConnectionState = "connecting" | "open" | "closing" | "closed";
109
```
110
111
**Usage Example:**
112
113
```typescript
114
// Connect with optional params
115
socket.connect({ room: "lobby" });
116
117
// Check connection status
118
if (socket.isConnected()) {
119
console.log("Socket is connected");
120
}
121
122
// Monitor connection state
123
const state = socket.connectionState();
124
console.log("Connection state:", state);
125
126
// Graceful disconnect
127
socket.disconnect(() => {
128
console.log("Disconnected gracefully");
129
}, 1000, "User logout");
130
```
131
132
### Event Handlers
133
134
Register callbacks for socket lifecycle events.
135
136
```typescript { .api }
137
/**
138
* Register callback for socket open events
139
* @param callback - Function to call when socket opens
140
* @returns Message reference for removing handler
141
*/
142
onOpen(callback: () => void | Promise<void>): MessageRef;
143
144
/**
145
* Register callback for socket close events
146
* @param callback - Function to call when socket closes
147
* @returns Message reference for removing handler
148
*/
149
onClose(callback: (event: CloseEvent) => void | Promise<void>): MessageRef;
150
151
/**
152
* Register callback for socket error events
153
* @param callback - Function to call when errors occur
154
* @returns Message reference for removing handler
155
*/
156
onError(callback: (
157
error: Event | string | number,
158
transport: new(endpoint: string) => object,
159
establishedConnections: number
160
) => void | Promise<void>): MessageRef;
161
162
/**
163
* Register callback for all socket messages
164
* @param callback - Function to call for each message
165
* @returns Message reference for removing handler
166
*/
167
onMessage(callback: (message: object) => void | Promise<void>): MessageRef;
168
169
/**
170
* Remove event handlers by reference
171
* @param refs - Array of message references to remove
172
*/
173
off(refs: MessageRef[]): void;
174
175
type MessageRef = string;
176
```
177
178
**Usage Example:**
179
180
```typescript
181
// Register event handlers
182
const openRef = socket.onOpen(() => {
183
console.log("Socket opened");
184
});
185
186
const closeRef = socket.onClose((event) => {
187
console.log("Socket closed:", event.code, event.reason);
188
});
189
190
const errorRef = socket.onError((error, transport, connections) => {
191
console.error("Socket error:", error);
192
console.log("Failed transport:", transport);
193
console.log("Established connections:", connections);
194
});
195
196
const messageRef = socket.onMessage((message) => {
197
console.log("Raw message:", message);
198
});
199
200
// Remove all handlers when done
201
socket.off([openRef, closeRef, errorRef, messageRef]);
202
```
203
204
### Channel Management
205
206
Create and manage channels through the socket.
207
208
```typescript { .api }
209
/**
210
* Create a channel for the given topic
211
* @param topic - Channel topic string (e.g., "room:lobby")
212
* @param chanParams - Channel-specific parameters
213
* @returns New Channel instance
214
*/
215
channel(topic: string, chanParams?: object): Channel;
216
217
/**
218
* Remove channel from socket
219
* @param channel - Channel instance to remove
220
*/
221
remove(channel: Channel): void;
222
```
223
224
**Usage Example:**
225
226
```typescript
227
// Create channels
228
const lobbyChannel = socket.channel("room:lobby", { user_id: 123 });
229
const userChannel = socket.channel("user:456", { permissions: ["read", "write"] });
230
231
// Remove channel when done
232
socket.remove(lobbyChannel);
233
```
234
235
### Utility Methods
236
237
Additional socket utility methods.
238
239
```typescript { .api }
240
/**
241
* Get protocol being used
242
* @returns Protocol string ("ws" or "wss")
243
*/
244
protocol(): string;
245
246
/**
247
* Get formatted endpoint URL
248
* @returns Complete WebSocket URL
249
*/
250
endPointURL(): string;
251
252
/**
253
* Replace the socket's transport mechanism
254
* @param transport - New transport constructor
255
*/
256
replaceTransport(transport: new(endpoint: string) => object): void;
257
258
/**
259
* Send raw data through socket
260
* @param data - Data object to send
261
*/
262
push(data: object): void;
263
264
/**
265
* Log message using configured logger
266
* @param kind - Log level/kind
267
* @param message - Log message
268
* @param data - Additional data to log
269
*/
270
log(kind: string, message: string, data: any): void;
271
272
/**
273
* Check if logger is configured
274
* @returns True if logger is available
275
*/
276
hasLogger(): boolean;
277
278
/**
279
* Generate unique message reference
280
* @returns Unique string reference
281
*/
282
makeRef(): MessageRef;
283
284
/**
285
* Ping server and measure latency
286
* @param callback - Function to receive latency measurement
287
* @returns True if ping was sent successfully
288
*/
289
ping: (callback: (latency: number) => void) => boolean;
290
```
291
292
**Usage Example:**
293
294
```typescript
295
// Get connection info
296
console.log("Protocol:", socket.protocol());
297
console.log("Endpoint:", socket.endPointURL());
298
299
// Generate unique reference
300
const ref = socket.makeRef();
301
console.log("Generated ref:", ref);
302
303
// Measure latency
304
socket.ping((latency) => {
305
console.log("Latency:", latency, "ms");
306
});
307
308
// Send raw data
309
socket.push({ event: "heartbeat", ref: socket.makeRef() });
310
311
// Check logging capability
312
if (socket.hasLogger()) {
313
socket.log("info", "Custom log message", { custom: "data" });
314
}
315
```