2 %%! -smp disable +A1 +K true -pa ebin deps/cowboy/ebin -input
3 -module(cowboy_multiplex).
9 -export([init/3, handle/2, terminate/2]).
13 application:start(sockjs),
14 application:start(cowboy),
16 MultiplexState = sockjs_multiplex:init_state(
17 [{"ann", fun service_ann/3, []},
18 {"bob", fun service_bob/3, []},
19 {"carl", fun service_carl/3, []}]),
21 SockjsState = sockjs_handler:init_state(
22 <<"/multiplex">>, sockjs_multiplex, MultiplexState, []),
24 VhostRoutes = [{[<<"multiplex">>, '...'], sockjs_cowboy_handler, SockjsState},
26 Routes = [{'_', VhostRoutes}], % any vhost
28 io:format(" [*] Running at http://localhost:~p~n", [Port]),
29 cowboy:start_listener(http, 100,
30 cowboy_tcp_transport, [{port, Port}],
31 cowboy_http_protocol, [{dispatch, Routes}]),
36 %% --------------------------------------------------------------------------
38 init({_Any, http}, Req, []) ->
42 {Path, Req1} = cowboy_http_req:path(Req),
43 {ok, Req2} = case Path of
44 [<<"multiplex.js">>] ->
45 {ok, Data} = file:read_file("./examples/multiplex/multiplex.js"),
46 cowboy_http_req:reply(200, [{<<"Content-Type">>, "application/javascript"}],
49 {ok, Data} = file:read_file("./examples/multiplex/index.html"),
50 cowboy_http_req:reply(200, [{<<"Content-Type">>, "text/html"}],
53 cowboy_http_req:reply(404, [],
54 <<"404 - Nothing here\n">>, Req1)
58 terminate(_Req, _State) ->
61 %% --------------------------------------------------------------------------
63 service_ann(Conn, init, State) ->
64 Conn:send("Ann says hi!"),
66 service_ann(Conn, {recv, Data}, State) ->
67 Conn:send(["Ann nods: ", Data]),
69 service_ann(_Conn, closed, State) ->
72 service_bob(Conn, init, State) ->
73 Conn:send("Bob doesn't agree."),
75 service_bob(Conn, {recv, Data}, State) ->
76 Conn:send(["Bob says no to: ", Data]),
78 service_bob(_Conn, closed, State) ->
81 service_carl(Conn, init, State) ->
82 Conn:send("Carl says goodbye!"),
85 service_carl(_Conn, _, State) ->