ws_handlers.ezdoc 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. ::: Handling Websocket connections
  2. A special handler is required for handling Websocket connections.
  3. Websocket handlers allow you to initialize the connection,
  4. handle incoming frames from the socket, handle incoming Erlang
  5. messages and then clean up on termination.
  6. Websocket handlers essentially act as a bridge between the client
  7. and the Erlang system. They will typically do little more than
  8. socket communication and decoding/encoding of frames.
  9. :: Initialization
  10. First, the `init/3` callback is called. This callback is common
  11. to all handlers. To establish a Websocket connection, this function
  12. must return an `upgrade` tuple.
  13. ``` erlang
  14. init(_, Req, Opts) ->
  15. {upgrade, protocol, cowboy_websocket}.
  16. ```
  17. It is also possible to return an update Req object and options
  18. using the longer form of this tuple.
  19. ``` erlang
  20. init(_Type, Req, Opts) ->
  21. {upgrade, protocol, cowboy_websocket, Req, Opts}.
  22. ```
  23. Upon receiving this tuple, Cowboy will switch to the code
  24. that handles Websocket connections. It does not immediately
  25. perform the handshake however. First, it calls the `websocket_init/3`
  26. callback.
  27. This function must be used to initialize the state, and can
  28. also be used to register the process, start a timer, etc.
  29. As long as the function returns an `ok` tuple, then Cowboy
  30. performs the Websocket handshake.
  31. ``` erlang
  32. websocket_init(_Type, Req, _Opts) ->
  33. {ok, Req, #state{}}.
  34. ```
  35. A `shutdown` tuple can be returned to refuse to perform the
  36. handshake. When doing so, Cowboy will send a `400 Bad Request`
  37. response to the client and close the connection.
  38. ``` erlang
  39. websocket_init(_Type, Req, _Opts) ->
  40. {shutdown, Req}.
  41. ```
  42. It is also possible to perform a `cowboy_req:reply/{2,3,4}`
  43. before returning a `shutdown` tuple, allowing you to override
  44. the response sent back to the client.
  45. Note that browser support for handling Websocket connection
  46. failures may vary.
  47. If the sec-websocket-protocol header was sent with the request
  48. for establishing a Websocket connection, then the Websocket
  49. handler *must* select one of these subprotocol and send it
  50. back to the client, otherwise the client might decide to close
  51. the connection, assuming no correct subprotocol was found.
  52. ``` erlang
  53. websocket_init(_Type, Req, _Opts) ->
  54. case cowboy_req:parse_header(<<"sec-websocket-protocol">>, Req) of
  55. {ok, undefined, Req2} ->
  56. {ok, Req, #state{}};
  57. {ok, Subprotocols, Req2} ->
  58. case lists:keymember(<<"mychat2">>, 1, Subprotocols) of
  59. true ->
  60. Req3 = cowboy:set_resp_header(<<"sec-websocket-protocol">>,
  61. <<"mychat2">>, Req2),
  62. {ok, Req3, #state{}};
  63. false ->
  64. {shutdown, Req2}
  65. end
  66. end.
  67. ```
  68. It is not recommended to wait too long inside the `websocket_init/3`
  69. function. Any extra initialization may be done after returning by
  70. sending yourself a message before doing anything. Any message sent
  71. to `self()` from `websocket_init/3` is guaranteed to arrive before
  72. any frames from the client.
  73. It is also very easy to ensure that this message arrives before
  74. any message from other processes by sending it before registering
  75. or enabling timers.
  76. ``` erlang
  77. websocket_init(_Type, Req, _Opts) ->
  78. self() ! post_init,
  79. %% Register process here...
  80. {ok, Req, #state{}}.
  81. websocket_info(post_init, Req, State) ->
  82. %% Perform post_init initialization here...
  83. {ok, Req, State}.
  84. ```
  85. :: Handling frames from the client
  86. Cowboy will call `websocket_handle/3` whenever a text, binary,
  87. ping or pong frame arrives from the client. Note that in the
  88. case of ping and pong frames, no action is expected as Cowboy
  89. automatically replies to ping frames.
  90. The handler can decide to send frames to the socket, shutdown
  91. or just continue without sending anything.
  92. The following snippet echoes back any text frame received and
  93. ignores all others.
  94. ``` erlang
  95. websocket_handle(Frame = {text, _}, Req, State) ->
  96. {reply, Frame, Req, State};
  97. websocket_handle(_Frame, Req, State) ->
  98. {ok, Req, State}.
  99. ```
  100. :: Handling Erlang messages
  101. Cowboy will call `websocket_info/3` whenever an Erlang message
  102. arrives.
  103. The handler can decide to send frames to the socket, shutdown
  104. or just continue without sending anything.
  105. The following snippet forwards any `log` message to the socket
  106. and ignores all others.
  107. ``` erlang
  108. websocket_info({log, Text}, Req, State) ->
  109. {reply, {text, Text}, Req, State};
  110. websocket_info(_Info, Req, State) ->
  111. {ok, Req, State}.
  112. ```
  113. :: Sending frames to the socket
  114. Cowboy allows sending either a single frame or a list of
  115. frames to the socket. Any frame can be sent: text, binary, ping,
  116. pong or close frames.
  117. The following example sends three frames using a single `reply`
  118. tuple.
  119. ``` erlang
  120. websocket_info(hello_world, Req, State) ->
  121. {reply, [
  122. {text, "Hello"},
  123. {text, <<"world!">>},
  124. {binary, <<0:8000>>}
  125. ], Req, State};
  126. %% More websocket_info/3 clauses here...
  127. ```
  128. Note that the payload for text and binary frames is of type
  129. `iodata()`, meaning it can be either a `binary()` or an
  130. `iolist()`.
  131. Sending a `close` frame will immediately initiate the closing
  132. of the Websocket connection. Be aware that any additional
  133. frames sent by the client or any Erlang messages waiting to
  134. be received will not be processed. Also note that when replying
  135. a list of frames that includes close, any frame found after the
  136. close frame will not be sent.
  137. :: Ping and timeout
  138. The biggest performance improvement you can do when dealing
  139. with a huge number of Websocket connections is to reduce the
  140. number of timers that are started on the server. A common use
  141. of timers when dealing with connections is for sending a ping
  142. every once in a while. This should be done exclusively on the
  143. client side. Indeed, a server handling one million Websocket
  144. connections will perform a lot better when it doesn't have to
  145. handle one million extra timers too!
  146. Cowboy will automatically respond to ping frames sent by the
  147. client. It will still forward the frame to the handler for
  148. informative purpose, but no further action is required.
  149. Cowboy can be configured to automatically close the Websocket
  150. connection when no data arrives on the socket. It is highly
  151. recommended to configure a timeout for it, as otherwise you
  152. may end up with zombie "half-connected" sockets that may
  153. leave the process alive forever.
  154. A good timeout value is 60 seconds.
  155. ``` erlang
  156. websocket_init(_Type, Req, _Opts) ->
  157. {ok, Req, #state{}, 60000}.
  158. ```
  159. This value cannot be changed once it is set. It defaults to
  160. `infinity`.
  161. :: Hibernate
  162. Most tuples returned from handler callbacks can include an
  163. extra value `hibernate`. After doing any necessary operations
  164. following the return of the callback, Cowboy will hibernate
  165. the process.
  166. It is highly recommended to hibernate processes that do not
  167. handle much traffic. It is a good idea to hibernate all
  168. connections by default and investigate only when you start
  169. noticing increased CPU usage.
  170. :: Supporting older browsers
  171. Unfortunately Websocket is a relatively recent technology,
  172. which means that not all browsers support it. A library like
  173. ^"Bullet^https://github.com/extend/bullet^ can be used to
  174. emulate Websocket connections on older browsers.