Cowboy is such a simple web framework.
This is a sample websocket app.
Use erlang.mk. Not that you have to, but it'd make things a bit easier.
First, create a folder for project, ex. myproject.
$ cd myproject/
Copy erlang.mk into it.
$ cp /my/erlang.mk/folder/erlang.mk .
$ make -f erlang.mk bootstrap bootstrap-rel
Edit generated Makefile.
PROJECT = myproject
DEPS = cowboy
include erlang.mk
Edit generated src/myproject.app.src
...
{applications: [
kernel,
stdlib,
cowboy
]},
...
Run make once, cowboy should be pulled to deps/ folder.
$ make
Then, we start adding cowboy code to main app file.
myproject_app.erl
Setup routing, direct "/websocket" to ws_handler.
start(_Type, _Args) ->
Dispatch = cowboy_router:compile([
{'_', [
{"/", cowboy_static, {priv_file, cowboy_websocket, "index.html"}},
{"/static/[...]", cowboy_static, {priv_dir, cowboy_websocket, "static"}},
{"/websocket", ws_handler, []}
]}
]),
{ok, _} = cowboy:start_http(ws_listener, 100, [{port, 8080}],
[{env, [{dispatch, Dispatch}]}]
),
cowboy_websocket_sup:start_link().
We route /websocket to ws_handler, now have make copy that websocket handler template.
$ make new t=cowboy_ws n=ws_handler
ws_handler.erl
Basically the template is good enough.
websocket_handle({text, Data}, Req, State) ->
io:format("received: ~w~n", [Data]),
{reply, {text, Data}, Req, State};
websocket_handle({binary, Data}, Req, State) ->
io:format("received: ~s~n", [Data]),
{reply, {binary, Data}, Req, State};
websocket_handle(_Frame, Req, State) ->
{ok, Req, State}.
$ make
$ cd _rel/myproject_release
$ ./bin/myproject_release console