Debian Codegraph @

doc/src/guide/ws_handlers.asciidoc

raw
1 [[ws_handlers]]
2 == Websocket handlers
3
4 Websocket handlers provide an interface for upgrading HTTP/1.1
5 connections to Websocket and sending or receiving frames on
6 the Websocket connection.
7
8 As Websocket connections are established through the HTTP/1.1
9 upgrade mechanism, Websocket handlers need to be able to first
10 receive the HTTP request for the upgrade, before switching to
11 Websocket and taking over the connection. They can then receive
12 or send Websocket frames, handle incoming Erlang messages or
13 close the connection.
14
15 === Upgrade
16
17 The `init/2` callback is called when the request is received.
18 To establish a Websocket connection, you must switch to the
19 `cowboy_websocket` module:
20
21 [source,erlang]
22 ----
23 init(Req, State) ->
24 {cowboy_websocket, Req, State}.
25 ----
26
27 Cowboy will perform the Websocket handshake immediately. Note
28 that the handshake will fail if the client did not request an
29 upgrade to Websocket.
30
31 The Req object becomes unavailable after this function returns.
32 Any information required for proper execution of the Websocket
33 handler must be saved in the state.
34
35 === Subprotocol
36
37 The client may provide a list of Websocket subprotocols it
38 supports in the sec-websocket-protocol header. The server *must*
39 select one of them and send it back to the client or the
40 handshake will fail.
41
42 For example, a client could understand both STOMP and MQTT over
43 Websocket, and provide the header:
44
45 ----
46 sec-websocket-protocol: v12.stomp, mqtt
47 ----
48
49 If the server only understands MQTT it can return:
50
51 ----
52 sec-websocket-protocol: mqtt
53 ----
54
55 This selection must be done in `init/2`. An example usage could
56 be:
57
58 [source,erlang]
59 ----
60 init(Req0, State) ->
61 case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req0) of
62 undefined ->
63 {cowboy_websocket, Req0, State};
64 Subprotocols ->
65 case lists:member(<<"mqtt">>, 1, Subprotocols) of
66 true ->
67 Req = cowboy_req:set_resp_header(<<"sec-websocket-protocol">>,
68 <<"mqtt">>, Req0),
69 {cowboy_websocket, Req, State};
70 false ->
71 Req = cowboy_req:reply(400, Req0),
72 {ok, Req, State}
73 end
74 end.
75 ----
76
77 === Post-upgrade initialization
78
79 Cowboy has separate processes for handling the connection
80 and requests. Because Websocket takes over the connection,
81 the Websocket protocol handling occurs in a different
82 process than the request handling.
83
84 This is reflected in the different callbacks Websocket
85 handlers have. The `init/2` callback is called from the
86 temporary request process and the `websocket_` callbacks
87 from the connection process.
88
89 This means that some initialization cannot be done from
90 `init/2`. Anything that would require the current pid,
91 or be tied to the current pid, will not work as intended.
92 The optional `websocket_init/1` can be used instead:
93
94 [source,erlang]
95 ----
96 websocket_init(State) ->
97 erlang:start_timer(1000, self(), <<"Hello!">>),
98 {ok, State}.
99 ----
100
101 All Websocket callbacks share the same return values. This
102 means that we can send frames to the client right after
103 the upgrade:
104
105 [source,erlang]
106 ----
107 websocket_init(State) ->
108 {[{text, <<"Hello!">>}], State}.
109 ----
110
111 === Receiving frames
112
113 Cowboy will call `websocket_handle/2` whenever a text, binary,
114 ping or pong frame arrives from the client.
115
116 The handler can handle or ignore the frames. It can also
117 send frames back to the client or stop the connection.
118
119 The following snippet echoes back any text frame received and
120 ignores all others:
121
122 [source,erlang]
123 ----
124 websocket_handle(Frame = {text, _}, State) ->
125 {[Frame], State};
126 websocket_handle(_Frame, State) ->
127 {ok, State}.
128 ----
129
130 Note that ping and pong frames require no action from the
131 handler as Cowboy will automatically reply to ping frames.
132 They are provided for informative purposes only.
133
134 === Receiving Erlang messages
135
136 Cowboy will call `websocket_info/2` whenever an Erlang message
137 arrives.
138
139 The handler can handle or ignore the messages. It can also
140 send frames to the client or stop the connection.
141
142 The following snippet forwards log messages to the client
143 and ignores all others:
144
145 [source,erlang]
146 ----
147 websocket_info({log, Text}, State) ->
148 {[{text, Text}], State};
149 websocket_info(_Info, State) ->
150 {ok, State}.
151 ----
152
153 === Sending frames
154
155 // @todo This will be deprecated and eventually replaced with a
156 // {Commands, State} interface that allows providing more
157 // functionality easily.
158
159 All `websocket_` callbacks share return values. They may
160 send zero, one or many frames to the client.
161
162 To send nothing, just return an ok tuple:
163
164 [source,erlang]
165 ----
166 websocket_info(_Info, State) ->
167 {ok, State}.
168 ----
169
170 To send one frame, return the frame to be sent:
171
172 [source,erlang]
173 ----
174 websocket_info(_Info, State) ->
175 {[{text, <<"Hello!">>}], State}.
176 ----
177
178 You can send frames of any type: text, binary, ping, pong
179 or close frames.
180
181 You can send many frames at the same time:
182
183 [source,erlang]
184 ----
185 websocket_info(_Info, State) ->
186 {[
187 {text, "Hello"},
188 {text, <<"world!">>},
189 {binary, <<0:8000>>}
190 ], State}.
191 ----
192
193 They are sent in the given order.
194
195 === Keeping the connection alive
196
197 Cowboy will automatically respond to ping frames sent by
198 the client. They are still forwarded to the handler for
199 informative purposes, but no further action is required.
200
201 Cowboy does not send ping frames itself. The handler can
202 do it if required. A better solution in most cases is to
203 let the client handle pings. Doing it from the handler
204 would imply having an additional timer per connection and
205 this can be a considerable cost for servers that need to
206 handle large numbers of connections.
207
208 Cowboy can be configured to close idle connections
209 automatically. It is highly recommended to configure
210 a timeout here, to avoid having processes linger longer
211 than needed.
212
213 The `init/2` callback can set the timeout to be used
214 for the connection. For example, this would make Cowboy
215 close connections idle for more than 30 seconds:
216
217 [source,erlang]
218 ----
219 init(Req, State) ->
220 {cowboy_websocket, Req, State, #{
221 idle_timeout => 30000}}.
222 ----
223
224 This value cannot be changed once it is set. It defaults to
225 `60000`.
226
227 === Limiting frame sizes
228
229 Cowboy accepts frames of up to 1MB in size by default.
230 You should limit the size depending on what your handler
231 may handle. You can do this via the `init/2` callback:
232
233 [source,erlang]
234 ----
235 init(Req, State) ->
236 {cowboy_websocket, Req, State, #{
237 max_frame_size => 8000000}}.
238 ----
239
240 The lack of limit is historical. A future version of
241 Cowboy will have a more reasonable default.
242
243 === Saving memory
244
245 The Websocket connection process can be set to hibernate
246 after the callback returns.
247
248 Simply add an `hibernate` field to the returned tuple:
249
250 [source,erlang]
251 ----
252 websocket_init(State) ->
253 {[], State, hibernate}.
254
255 websocket_handle(_Frame, State) ->
256 {[], State, hibernate}.
257
258 websocket_info(_Info, State) ->
259 {[{text, <<"Hello!">>}], State, hibernate}.
260 ----
261
262 It is highly recommended to write your handlers with
263 hibernate enabled, as this allows to greatly reduce the
264 memory usage. Do note however that an increase in the
265 CPU usage or latency can be observed instead, in particular
266 for the more busy connections.
267
268 === Closing the connection
269
270 The connection can be closed at any time, either by telling
271 Cowboy to stop it or by sending a close frame.
272
273 To tell Cowboy to close the connection, use a stop tuple:
274
275 [source,erlang]
276 ----
277 websocket_info(_Info, State) ->
278 {stop, State}.
279 ----
280
281 Sending a `close` frame will immediately initiate the closing
282 of the Websocket connection. Note that when sending a list of
283 frames that include a close frame, any frame found after the
284 close frame will not be sent.
285
286 The following example sends a close frame with a reason message:
287
288 [source,erlang]
289 ----
290 websocket_info(_Info, State) ->
291 {[{close, 1000, <<"some-reason">>}], State}.
292 ----