Skip to content

Instantly share code, notes, and snippets.

@Sephi-Chan
Last active December 15, 2015 15:59
Show Gist options
  • Save Sephi-Chan/5285961 to your computer and use it in GitHub Desktop.
Save Sephi-Chan/5285961 to your computer and use it in GitHub Desktop.
-module(seelies_server_websocket_handler).
-behaviour(cowboy_websocket_handler).
-export([ init/3, websocket_init/3, websocket_handle/3, websocket_info/3, websocket_terminate/3 ]).
-record(connection, { id, name = none }).
-include("../include/constants.hrl").
init({ tcp, http }, _Request, _Options) ->
{ upgrade, protocol, cowboy_websocket }.
websocket_init(_TransportName, Request, _Options) ->
State = #connection{ id = erlang:make_ref() },
io:format("New connection ~p is created.~n", [ State#connection.id ]),
gproc:add_local_property(room, ignored),
{ ok, Request, State }.
websocket_handle({ text, Message }, Request, State) ->
{ _Type, _Reply, NewState } = parseAction(mochijson3:decode(Message), State),
io:format("~p~n~p~n", [ NewState, self() ]),
{ ok, Request, NewState }.
websocket_info({ push_json, Json }, Request, State) ->
{ reply, { text, Json }, Request, State };
websocket_info(Info, Request, State) ->
io:format("~p~n", [ Info ]),
{ ok, Request, State }.
websocket_terminate(_Reason, _Request, State) ->
io:format("Socket holding connection ~p (named ~p) is closed.~n", [ State#connection.id, State#connection.name ]),
ok.
parseAction([ ?CHOOSE_NAME, Name ], State) ->
io:format("~p~n", [ State#connection.id ]),
case Pid = gproc:lookup_local_name({ connection, Name }) of
undefined ->
gproc:add_local_name({ connection, Name }),
OtherUsers = [],
push_json([ ?CONNECTED, OtherUsers ]),
{ json, ok, State#connection{ name = Name } };
_ ->
push_json([ ?NAME_TAKEN ]),
{ json, ok, State }
end;
parseAction(Message, State) ->
io:format("Unkown action ~p.~n", [ Message ]),
{ error, none, State }.
push_json(Content) ->
Json = mochijson3:encode(Content),
self() ! { push_json, Json }.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment