Last active
January 1, 2016 04:09
-
-
Save umurgdk/8089759 to your computer and use it in GitHub Desktop.
websocket handler for cowboy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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