websocket-railsで特定グループにメッセージを送信する †準備 †websocket-railsインストール を参照して環境構築 サーバ処理の作成 †WebSocketイベント定義 †config/events.rb subscribe :notify_group , 'messages#notify_group' WebScoketコントローラ作成 †app/controller/messages_controller.rb class MessagesController < WebsocketRails::BaseController # # グループ通知 # def notify_group logger.debug("notify_group!"); # 未ログイン時は何もしない if !current_user return end channel_name = message[:gid] msg = message[:msg] from_uid = current_user.id from_user = User.find(from_uid) from_email = from_user[:email] logger.debug("channel_name : " + channel_name.to_s ) online_channel = false if WebsocketRails.channel_manager && WebsocketRails.channel_manager.channels WebsocketRails.channel_manager.channels.each do |key,channel| if key.to_s == channel_name.to_s online_channel = true end end end if online_channel WebsocketRails[channel_name].trigger(:notification, { :msg => msg, :from => from_email , :type => "group" }) logger.debug("group notify OK!(" + channel_name + ")"); trigger_success({ :msg => "send OK!"}) else # 通知失敗時 logger.debug("notify error!"); trigger_failure({ :error => "error!"}) end end . . end 共通処理(js)の作成 †app/assets/javascript/_common.js jQuery(function($){ var myapp = window.myapp = window.myapp || {}; /** * グループ通知のsubscribe */ myapp.subscribe_channels = function(channels){ if (!channels || channels.length == 0){ return; } for (var i in channels) { var channel_name = channels[i]; console.log("subscribe_channels " + channel_name); myapp.channel = myapp.dispatcher.subscribe(channel_name); myapp.channel.bind('notification', function(data) { console.log('channel event received'); myapp.showNotifyDialog(data); }); } }; }); メッセージ送信用画面の作成 †コントローラの作成 †app/controller/chats_controller.rb class ChatsController < ApplicationController # # グループ一覧を表示する # def groups @groups = group_list @gid = params[:gid] || nil @msg = params[:msg] || nil if request.post? to_group end end private # # グループ一覧を取得する. # def group_list groups = [] online_groups = [] WebsocketRails.channel_manager.channels.each do |key,channel| logger.debug("key :" + key.to_s) online_groups << key.to_s end logger.debug(online_groups.to_s) all_groups = Group.all all_groups.each do |g| #rec = g.attributes.compact! rec = g.attributes rec["status"] = online_groups.include?(rec["channel_name"]) groups << rec end groups end ビューの作成 †app/views/chats/users.html.erb <h3>グループを指定してメッセージを送信する</h3> <%= render :partial => "shared/messages" %> <%= form_tag('/chats/groups', :method => :post, :id => "sendto_group_form") do %> <div>グループ</div> <table class="tbl"> <thead> <tr> <th> </th> <th>グループ</th> <th>オンライン</th> </tr> </thead> <tbody> <% if @groups %> <% @groups.each do |g| %> <tr> <td><input type="radio" name="gid" value="<%= g["channel_name"] %>" /></td> <td><%= g["name"] %></td> <td><%= g["status"] ? "◯" : "" %></td> </tr> <% end %> <% end %> </tbody> </table> <br /> <div>メッセージ</div> <div> <textarea name="msg" rows="5" cols="40"><%= @msg %></textarea> </div> <input id="btn_ws" type="button" value="Websocket送信" /> <% end %> クライアント処理の作成 †app/assets/javascript/chats/users.js jQuery(function($){ /** * [websocket送信] */ $(document).on("click", "#sendto_group_form #btn_ws", function(e){ var data = { "gid" : $("form").find("[name=gid]:checked").val(), "msg" : $("form").find("[name=msg]").val() }; myapp.dispatcher.trigger("notify_group", data, function(data){ myapp.showInfo("送信しました。"); }, function(data){ myapp.showError("送信できませんでした。"); } ); }); // ws接続 myapp.wsConnect(); // subscribe myapp.subscribe_default(); }); |