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.

在线测试http://www.baiyangliu.com/lab/websocket/

本地websocket测试地址

ws://127.0.0.1:8080/websocket

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

原文地址:https://www.cnblogs.com/ziyouchutuwenwu/p/4197847.html