您好,欢迎来到宝玛科技网。
搜索
您的当前位置:首页erlang的websocket例子

erlang的websocket例子

来源:宝玛科技网

创建工程

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.

在线测试

ws://127.0.0.1:8080/websocket

文本消息和binary消息自己打印慢慢看即可

 

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baomayou.com 版权所有 赣ICP备2024042794号-6

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务