Skip to content

Instantly share code, notes, and snippets.

@umurgdk
Last active January 1, 2016 04:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umurgdk/8089759 to your computer and use it in GitHub Desktop.
Save umurgdk/8089759 to your computer and use it in GitHub Desktop.
websocket handler for cowboy
defmodule CowboyBook.Handlers.Status do
def init({:tcp, :http}, req, opts) do
{:upgrade, :protocol, :cowboy_websocket}
end
def websocket_init(transport_name, req, _opts) do
:erlang.start_timer(1000, self(), "Hello!")
{:ok, req, nil}
end
def websocket_handle({:text, msg}, req, state) do
case JSON.decode(msg) do
{:ok, result} -> handle_message(result["message"], result["data"], req, state)
other -> {:reply, {:text, "Message: #{msg}"}, req, state}
end
end
def websocket_handle(_data, req, state) do
{:ok, req, state}
end
def websocket_info({:timeout, _ref, msg}, req, state) do
:erlang.start_timer(1000, self(), "Are you there!")
{:reply, {:text, msg}, req, state}
end
def websocket_info(_info, req, state) do
{:ok, req, state}
end
def websocket_terminate(_reason, _req, _state), do: :ok
defp handle_message("join", data, req, state) do
# todo: make user join
{:ok, req, state}
end
defp handle_message("talk", data, req, state) do
# todo: send message to user
{:ok, req, state}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment