WebアプリにPusherを用いて、リアルタイム通信機能を実装するやり方を教えてください。
・やりたいこと
LINEやFacebookメッセンジャーのようなリアルタイム通信をPusherで実装したい。
ユーザAがformからメッセージを投稿すると、ユーザBの画面にリアルタイムにメッセージが反映される。
・環境
Ruby/Rails4.2 ※DEVISE導入済み
・サーバ
heroku
・わからないこと
herokuのAdd-onsからPusherを導入しましたが、メッセージの反映がリアルタイムではなく、ユーザAがformからメッセージを投稿しても、ユーザBの画面ではブラウザをリロードしないとメッセージが反映されません。どのようにすればリアルタイムでお互いのメッセージが画面に反映されるのか教えて頂きたいです。
index.html.erb
<script src="https://js.pusher.com/3.0/pusher.min.js"></script> <script> // Enable pusher logging - don't include this in production Pusher.log = function(message) { if (window.console && window.console.log) { window.console.log(message); } }; var pusher = new Pusher('自分のAPI Key', { encrypted: true }); var channel = pusher.subscribe('test_channel'); channel.bind('my_event', function(data) { alert(data.message); }); </script>config/initializers/pusher.rb
require 'pusher'
Pusher.app_id = 'hoge'
Pusher.key = 'hoge'
Pusher.secret = 'hoge'
Pusher.logger = Rails.logger
Pusher.encrypted = true
app/controllers/hello_world_controller.rb
class HelloWorldController < ApplicationController
def hello_world
Pusher.trigger('test_channel', 'my_event', {
message: 'hello world'
})
end
end
宜しくお願い致します。
あなたの回答
tips
プレビュー