WebSock
WebSock is a library & specification for apps to service WebSocket connections; you can think
of it as 'Plug for WebSockets'. WebSock abstracts WebSocket support from servers such as
Bandit or Cowboy
and exposes a generic WebSocket API to applications. WebSocket-aware
applications such as Phoenix can then be hosted within a supported web server
simply by defining conformance to the WebSock behaviour, in the same manner as
how Plug conformance allows their HTTP aspects to be hosted within an arbitrary
web server.
WebSocket consists of two parts:
The
WebSockbehaviour describes the functions that an application such as Phoenix must implement in order to be WebSock compliant; it is roughly the equivalent of thePluginterface, but for WebSocket connectionsThe
WebSocklibrary implements transparent adapters to translate server-specific APIs into theWebSockbehaviour (currently, Bandit and Cowboy are supported)
WebSocket Lifecycle
WebSocket connections go through a well defined lifecycle mediated by WebSock:
- This step is outside the scope of the WebSock API. A client will attempt to Upgrade an HTTP connection to a WebSocket connection by passing a specific set of headers in an HTTP request. An application may choose to determine the feasibility of such an upgrade request however it pleases
- An application will then signal an upgrade to be performed by calling
WebSock.upgrade/4, passing in thePlug.Connto upgrade, along with theWebSockcompliant handler module which will handle the connection once it is upgraded - The underlying server will then attempt to upgrade the HTTP connection to a WebSocket connection
- Assuming the WebSocket connection is successfully negotiated, WebSock will
call
c:WebSock.init/1on the configured handler to allow the application to perform any necessary tasks now that the WebSocket connection is live - WebSock will call the configued handler's
c:WebSock.handle_in/2callback whenever data is received from the client - WebSock will call the configued handler's
c:WebSock.handle_info/2callback whenever other processes send messages to the handler process - The
WebSockimplementation can send data to the client by returning a{:push,...}tuple from any of the abovehandle_*callback - At any time,
c:WebSock.terminate/2may be called to indicate a close, error or timeout condition
For more information, consult the docs.
Installation
The websock package can be installed by adding websock to your list of dependencies in mix.exs:
def deps do
[
{:websock, "~> 0.4.1"}
]
end
Documentation can be found at https://hexdocs.pm/websock.
License
MIT