Skip to content

Instantly share code, notes, and snippets.

@jcfrank
Last active November 3, 2022 07:15
Show Gist options
  • Save jcfrank/8f9356b2fed1dd3be2c1 to your computer and use it in GitHub Desktop.
Save jcfrank/8f9356b2fed1dd3be2c1 to your computer and use it in GitHub Desktop.
A simple erlang cowboy websocket app

Simple Cowboy websocket app

Cowboy is such a simple web framework.
This is a sample websocket app.

new project

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}.

Run

$ make
$ cd _rel/myproject_release
$ ./bin/myproject_release console

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment