cowboy实现websocket
.
然后和WebSocket握手。-module(websocket_app). -behaviour(application). %% Application callbacks
-export([start/, stop/]). %% ===================================================================
%% Application callbacks
%% =================================================================== start(_StartType, _StartArgs) ->
%%启动存储pid的树据 可以采用 ets 表格处理 但是为了方便集群处理 我采用的mnesia
ok = websocket_store:init(),
%% 配置路由
Dispatch = cowboy_router:compile([
{'_', [
{"/", cowboy_static, {priv_file, websocket, "index.html"}},
{"/websocket", websocket_hander, []},
{"/static/[...]", cowboy_static, {priv_dir, websocket, "static"}}
]}
]),
{ok, _} = cowboy:start_http(http, , [{port, }],
[{env, [{dispatch, Dispatch}]}]),
%%启动监督树
websocket_sup:start_link(). stop(_State) ->
ok.
-module(websocket_sup). -behaviour(supervisor). %% API
-export([start_link/]). %% Supervisor callbacks
-export([init/]). %% Helper macro for declaring children of supervisor
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, , Type, [I]}). %% ===================================================================
%% API functions
%% =================================================================== start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []). %% ===================================================================
%% Supervisor callbacks
%% =================================================================== init([]) ->
Children = [],
{ok, { {one_for_one, , }, Children} }.
-module(websocket_hander). -behaviour(cowboy_websocket_handler). %% ------------------------------------------------------------------
%% API Function Exports
%% ------------------------------------------------------------------ %% ------------------------------------------------------------------
%% gen_server Function Exports
%% ------------------------------------------------------------------ -export([init/]).
-export([websocket_init/]).
-export([websocket_handle/]).
-export([websocket_info/]).
-export([websocket_terminate/]). %% ------------------------------------------------------------------
%% API Function Definitions
%% ------------------------------------------------------------------ %% ------------------------------------------------------------------
%% gen_server Function Definitions
%% ------------------------------------------------------------------ %%websocket 握手
init({tcp, http}, _Req, _Opts) ->
%%插入数据
websocket_store:dirty_insert(self(),web),
{upgrade, protocol, cowboy_websocket}.
%%连接初始
websocket_init(_TransportName, Req, _Opts) ->
%%连接一秒后 发送消息
erlang:start_timer(, self(), <<"Hello!">>),
{ok, Req, undefined_state}.
%%处理客户端发送投递的消息
websocket_handle({text, Msg}, Req, State) ->
%% 把消息投递到其余的进程 这里可以 投递到 tcp socket 也可以投递的 websocket 这样就可以实现 服务支持多协议处理
lists:foreach(fun([Pid,SocketType]) ->
case SocketType of
tcp -> ok;
web ->
case Pid == self() of
true -> ok;
false -> Pid!{chat,Msg}
end
end
end,websocket_store:dirty_lookall()),
{reply, {text, << "That's what she said! ", Msg/binary >>}, Req, State};
websocket_handle(_Data, Req, State) ->
{ok, Req, State}.
%% 处理erlang 发送的消息 这里是接收 行发送的数据
websocket_info({chat,Msg},_Req,State)->
{reply,{text,Msg},_Req,State};
%% 处理 erlang:start_timer(, self(), <<"Hello!">>) 发送的消息
websocket_info({timeout, _Ref, Msg}, Req, State) ->
{reply, {text, Msg}, Req, State}; websocket_info(_Info, Req, State) ->
{ok, Req, State}.
%%断开socket
websocket_terminate(_Reason, _Req, _State) ->
websocket_store:dirty_delete(self()),
ok. %% ------------------------------------------------------------------
%% Internal Function Definitions
%% ------------------------------------------------------------------
%%%-------------------------------------------------------------------
%%% @author thinkpad <>
%%% @copyright (C) , thinkpad
%%% @doc
%%%
%%% @end
%%% Created : Jun by thinkpad <>
%%%-------------------------------------------------------------------
-module(websocket_store). -include_lib("stdlib/include/qlc.hrl" ).
%% API
-export([dirty_insert/,dirty_lookall/,dirty_lookall_record/,dirty_delete/]). -export([init/,insert/,delete/,lookup/,lookall/]). -record(socket_to_pid, {pid,socket_type}). -define(WAIT_FOR_TABLES, ). %%%===================================================================
%%% API
%%%===================================================================
init()->
dynamic_db_init(). %--------------------------------------------------------------------
%% @doc Insert a key and pid.
%% @spec insert(Key, Pid) -> void()
%% @end
%%--------------------------------------------------------------------
insert(Pid,SocketType) when is_pid(Pid) ->
Fun = fun() -> mnesia:write(#socket_to_pid{pid = Pid, socket_type = SocketType}) end,
{atomic, _} = mnesia:transaction(Fun). %--------------------------------------------------------------------
%% @doc dirty insert pid and socket
%% @spec dirty_insert(Pid socket)
%% @end
%%-------------------------------------------------------------------- dirty_insert(Pid,SocketType) when is_pid(Pid) ->
mnesia:dirty_write(#socket_to_pid{pid = Pid, socket_type = SocketType}).
%--------------------------------------------------------------------
%% @doc dirty_read data
%% @spec dirty_lookall()
%% @end
%%-------------------------------------------------------------------- dirty_lookall()->
mnesia:dirty_select(socket_to_pid,[{#socket_to_pid{pid='$1',socket_type = '$2'},[],['$$']}]). dirty_delete(Pid)->
mnesia:dirty_delete(socket_to_pid,Pid). %--------------------------------------------------------------------
%% @doc look all record info
%% @spec
%% @end
%%-------------------------------------------------------------------- dirty_lookall_record()->
mnesia:dirty_select(socket_to_pid,[{#socket_to_pid{pid='$1',socket_type = '$2'},[],['$_']}]).
%%--------------------------------------------------------------------
%% @doc Find a pid given a key.
%% @spec lookup(Key) -> {ok, Pid} | {error, not_found}
%% @end
%%--------------------------------------------------------------------
lookup(Pid) ->
do(qlc:q([{X#socket_to_pid.pid,X#socket_to_pid.socket_type} || X <- mnesia:table(socket_to_pid),X#socket_to_pid.pid==Pid])). %%--------------------------------------------------------------------
%% @doc Find all list
%% @spec lookall() -> {List} | {error, not_found}
%% @end
%%--------------------------------------------------------------------
lookall() ->
do(qlc:q([[X#socket_to_pid.pid,X#socket_to_pid.socket_type] || X <- mnesia:table(socket_to_pid)])). %%--------------------------------------------------------------------
%% @doc Delete an element by pid from the registrar.
%% @spec delete(Pid) -> void()
%% @end
%%--------------------------------------------------------------------
delete(Pid) ->
try
[#socket_to_pid{} = Record] = mnesia:dirty_read(socket_to_pid, Pid, #socket_to_pid.pid),
mnesia:dirty_delete_object(Record)
catch
_C:_E -> ok
end. %%--------------------------------------------------------------------
%% @doc
%% @spec
%% @end
%%-------------------------------------------------------------------- %%%===================================================================
%%% Internal functions
%%%===================================================================
dynamic_db_init() ->
delete_schema(),
{atomic, ok} = mnesia:create_table(socket_to_pid, [{attributes, record_info(fields, socket_to_pid)}]),
ok. %% deletes a local schema.
delete_schema() ->
mnesia:stop(),
mnesia:delete_schema([node()]),
mnesia:start(). do(Query) ->
F = fun() -> qlc:e(Query) end,
{atomic, Value} = mnesia:transaction(F),
Value.
cowboy实现websocket的更多相关文章
- Cowboy 开源 WebSocket 网络库
Cowboy.WebSockets 是一个托管在 GitHub 上的基于 .NET/C# 实现的开源 WebSocket 网络库,其完整的实现了 RFC 6455 (The WebSocket Pro ...
- 【转】Cowboy 开源 WebSocket 网络库
原文链接: http://www.cnblogs.com/gaochundong/p/cowboy_websockets.html
- [Erlang33]使用recon从网页查看Erlang运行状态
0.需求分析 Erlang最好的卖点之一就是提供了一个非常强大的shell来查看Node运行时的各种状态,可以进行各种各样的内部查看,在运行时调试和分析,热更新代码. 但是总有一些在生产环境下要慎 ...
- Erlang cowboy websocket 服务器
Erlang cowboy websocket 服务器 原文见于: http://marcelog.github.io/articles/erlang_websocket_server_cowboy_ ...
- Cowboy http服务器 websocket
一.基础介绍 cowboy是一个小巧.快速.模块化的http服务器,采用Erlang开发.其中良好的clean module使得我们可以扩展到多种网络协议之中,cowboy自带的有tcp和ssl,而也 ...
- [翻译][erlang]cowboy handler模块的使用
关于Cowboy Cowboy是基于Erlang实现的一个轻量级.快速.模块化的http web服务器. Handlers,用于处理HTTP请求的程序处理模块. Plain HTTP Handlers ...
- Erlang cowboy 入门参考之现代Web的发展历史
Erlang cowboy 入门参考之现代Web发展史 原文: http://ninenines.eu/docs/en/cowboy/1.0/guide/modern_web/ 让我回顾一下web技术 ...
- Erlang cowboy 入门参考
Erlang cowboy 入门参考 cheungmine,2014-10-28 本文翻译自: http://ninenines.eu/docs/en/cowboy/HEAD/guide/gettin ...
- 带ssl的websocket例子
还是在那个websocket_demo的例子 rebar-creator create-app websocket_demo tree一下看看大概目录 ├── cert │ ├── cowboy- ...
随机推荐
- Wireshark(一):Wireshark基本用法
转载:https://community.emc.com/message/818739#818739 按照国际惯例,从最基本的说起. 抓取报文: 下载和安装好Wireshark之后,启动Wiresha ...
- mac相关记录
一.设置允许安装任何来源软件 命令行执行: sudo spctl --master-disable -----------------------------
- Chrome浏览器快捷键
Chrome窗口和标签页快捷键:Ctrl+N 打开新窗口 Ctrl+T 打开新标签页 Ctrl+Shift+N 在隐身模式下打开新窗口 Ctrl+O,然后选择文件 在谷歌浏览器中打开计算机上的文件 按 ...
- zabbix监控php-fpm的性能
zabbix监控php-fpm主要是通过nginx配置php-fpm的状态输出页面,在正则取值 要nginx能输出php-fpm的状态必须要先修改php-fpm的配置,这个配置没有开启nginx 就没 ...
- mysql 进阶查询(学习笔记)
学习笔记,来源:实验楼 ,链接: https://www.shiyanlou.com/courses/9 一.日期计算: 1.要想确定每个宠物有多大,可以使用函数TIMESTAMPDIFF()计算 ...
- Java JDBC概要总结一(基本操作和SQL注入问题)
JDBC定义: JDBC(Java DataBase Connectivity,java数据库连接)是一种用于执行SQL语句的Java API.JDBC是Java访问数据库的标准规范,可以为不同的关系 ...
- Mysql导出数据结构 or 数据
如果我们单单只想导出mysql数据表结构,通过navcat工具还不行,这时我们可以用mysqldump工具 在mysql server的安装目录:C:\Program Files\MySQL\MySQ ...
- share point CSOM 客户端模式 创建 list
/// <summary> /// 创建新的列表 list /// </summary> /// <param name="web"></ ...
- Softmax回归 softMax回归与logistic回归的关系
简介 在本节中,我们介绍Softmax回归模型,该模型是logistic回归模型在多分类问题上的推广,在多分类问题中,类标签 可以取两个以上的值. Softmax回归模型对于诸如MNIST手写数字分 ...
- 清除微信浏览器网址的缓存,cookie
清理微信浏览网站的缓存,Cookie http://blog.csdn.net/cui55/article/details/53939462 怎么清除IOS微信浏览器中的cookie? 退出微信重新登 ...