Created
September 6, 2013 04:24
-
-
Save mathieul/6459540 to your computer and use it in GitHub Desktop.
Example of websocket handler
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 ApplicationRouter do | |
use Dynamo.Router | |
prepare do | |
conn.fetch([:params]) | |
end | |
post "/publish" do | |
room_id = conn.params[:room_id] | |
data = conn.params[:data] | |
if room_id && data do | |
Chaussette.Pubsub.publish(room_id, data) | |
conn.resp 200, "Message sent." | |
else | |
conn.resp 406, "Not Acceptable" | |
end | |
end | |
websocket "/web-socket", using: Chaussette.WebsocketHandler | |
end |
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
class Updater | |
constructor: (options) -> | |
{roomId, websocketUrl} = options | |
@setup("#{websocketUrl}?room_id=#{roomId}") | |
setup: (url) -> | |
@ws = new WebSocket(url) | |
@ws.onmessage = (evt) => @onMessage JSON.parse(evt.data) | |
destroy: -> | |
@ws?.close() | |
onMessage: (data) -> | |
console.log "received message:", data | |
# update something using data content | |
# ... | |
@App.Updater = Updater |
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 Chaussette.WebsocketHandler do | |
@behaviour :cowboy_websocket_handler | |
alias Chaussette.Pubsub | |
def websocket_init(_transport_name, req, [ conn: conn ]) do | |
room_id = conn.params[:room_id] | |
if room_id, do: Pubsub.register(room_id, self) | |
{ :ok, req, [ room: room_id ] } | |
end | |
def websocket_handle( { :text, message }, req, state) do | |
{ :reply, {:text, message }, req, state } | |
end | |
def websocket_handle(_data, req, state), do: { :ok, req, state} | |
def websocket_info({ :pubsub_message, message }, req, state) do | |
{ :reply, { :text, message }, req, state } | |
end | |
def websocket_info(_data, req, state), do: { :ok, req, state } | |
def websocket_terminate(_reason, _req, state) do | |
[ room: room ] = state | |
Pubsub.unregister(room, self) | |
:ok | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment