• 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消息自己打印慢慢看即可

  • 相关阅读:
    Hz赫兹的定义
    NetCore 迅速接入微信支付+支付宝支付 payLink C# 交差并集
    C# 生产随机数 --几乎可以做到不重复
    Spark MLib完整基础入门教程
    (转)Scrapy 教程
    (转)python自顶向下设计步骤_python实现自顶向下,自底向上
    (转)scrapy架构图与执行流程
    (转)Python:字典(zip, dict)
    (转)APUE第13章 守护进程Deameon
    (转)Python开发指南
  • 原文地址:https://www.cnblogs.com/ziyouchutuwenwu/p/4197847.html
Copyright © 2020-2023  润新知