创建工程
rebar-creator create-app websocket_demo
文件列表
route_helper.erl
-module(route_helper). -export([get_routes/0]). get_routes() -> [ {'_', [ {"/websocket", ws_handler, []} ]} ].
websocket_demo_app.erl
-module(websocket_demo_app). -behaviour(application). -export([start/2, stop/1]). start(_Type, _Args) -> ok = application:start(crypto), ok = application:start(cowlib), ok = application:start(ranch), ok = application:start(cowboy), Routes = route_helper:get_routes(), Dispatch = cowboy_router:compile(Routes), Port = 8080, TransOpts = [{port, Port}], ProtoOpts = [{env, [{dispatch, Dispatch}]}], cowboy:start_http(http, 100, TransOpts, ProtoOpts). stop(_State) -> ok.
ws_handler.erl
-module(ws_handler). -behaviour(cowboy_websocket_handler). -export([init/3]). -export([websocket_init/3]). -export([websocket_handle/3]). -export([websocket_info/3]). -export([websocket_terminate/3]). init({tcp, http}, _Req, _Opts) -> io:format("init ~n"), {upgrade, protocol, cowboy_websocket}. websocket_init(_TransportName, Req, _Opts) -> io:format("websocket_init ~n"), erlang:start_timer(1000, self(), <<"Hello!">>), {ok, Req, undefined_state}. websocket_handle({text, Msg}, Req, State) -> %% io:format("websocket_handle text ~p,~p,~p~n",[Msg,Req,State]), {reply, {text, << "That's what she said! ", Msg/binary >>}, Req, State}; websocket_handle(_Data, Req, State) -> %% io:format("websocket_handle ~p,~p,~p~n",[_Data,Req,State]), {ok, Req, State}. websocket_info({timeout, _Ref, Msg}, Req, State) -> %io:format("websocket timeout ~n"), erlang:start_timer(1000, self(), <<"How' you doin'?">>), {reply, {text, Msg}, Req, State}; websocket_info(_Info, Req, State) -> io:format("websocket_info ~p,~p,~p~n",[_Info,Req,State]), {ok, Req, State}. websocket_terminate(_Reason, _Req, _State) -> io:format("terminate ~n"), ok.
在线测试http://www.baiyangliu.com/lab/websocket/
本地websocket测试地址
ws://127.0.0.1:8080/websocket
文本消息和binary消息自己打印慢慢看即可
android需要4.2以上的webkit才支持websocket,但是cocos2d的websocket库在mac,ios,android测试连接我的这个erlang服务器都会报下面的错误
websocket_terminate {error,closed}
但是他连接官方的websocket.org就没事,我的websocket服务器用在线测试,不管在mac,ios,android4.2以上,都没问题
无奈了……
继续原始的socket吧,这个肯定是万能的了,唉……