以下は、em-websocket、websocket-rails (長い間維持されていなかった)、 faye -websocket-railsおよびActionCableへの参照を含むChase Gilliam の簡潔な回答に追加されます。
Pleziフレームワークをお勧めします。これは、独立したアプリケーション フレームワークとしても、Rails Websocket 拡張機能としても機能します。
また、次の点についても検討します。
接続間でメッセージを保持する必要がありますか (つまり、他のユーザーがオフラインの場合、メッセージは「メッセージ ボックス」で待機する必要がありますか?メッセージはどのくらい待機する必要がありますか?)...?
メッセージ履歴を保持しますか?
これらのポイントは、メッセージに永続的なストレージ (データベースなど) を使用するかどうかを決定するのに役立ちます。
つまり、Rails でPleziinit_plezi.rb
を使用するには、アプリケーションのconfig/initializers
フォルダに を作成します。(例として) 次のコードを使用します。
class ChatDemo
# use JSON events instead of raw websockets
@auto_dispatch = true
protected #protected functions are hidden from regular Http requests
def auth msg
@user = User.auth_token(msg['token'])
return close unless @user
# creates a websocket "mailbox" that will remain open for 9 hours.
register_as @user.id, lifetime: 60*60*9, max_connections: 5
end
def chat msg, received = false
unless @user # require authentication first
close
return false
end
if received
# this is only true when we sent the message
# using the `broadcast` or `notify` methods
write msg # writes to the client websocket
end
msg['from'] = @user.id
msg['time'] = Plezi.time # an existing time object
unless msg['to'] && registered?(msg['to'])
# send an error message event
return {event: :err, data: 'No recipient or recipient invalid'}.to_json
end
# everything was good, let's send the message and inform
# this will invoke the `chat` event on the other websocket
# notice the `true` is setting the `received` flag.
notify msg['to'], :chat, msg, true
# returning a String will send it to the client
# when using the auto-dispatch feature
{event: 'message_sent', msg: msg}.to_json
end
end
# remember our route for websocket connections.
route '/ws_chat', ChatDemo
# a route to the Javascript client (optional)
route '/ws/client.js', :client
Plezi は独自のサーバー (Iodine、Ruby サーバー) をセットアップするため、アプリケーションからやその他のカスタム サーバーへpuma
の参照を削除することを忘れないでください。thin
クライアント側では、Plezi が提供する Javascript ヘルパーを使用したい場合があります (オプションです)... 追加:
<script src='/es/client.js' />
<script>
TOKEN = <%= @user.token %>;
c = new PleziClient(PleziClient.origin + "/ws_chat") // the client helper
c.log_events = true // debug
c.chat = function(event) {
// do what you need to print a received message to the screen
// `event` is the JSON data. i.e.: event.event == 'chat'
}
c.error = function(event) {
// do what you need to print a received message to the screen
alert(event.data);
}
c.message_sent = function(event) {
// invoked after the message was sent
}
// authenticate once connection is established
c.onopen = function(event) {
c.emit({event: 'auth', token: TOKEN});
}
// // to send a chat message:
// c.emit{event: 'chat', to: 8, data: "my chat message"}
</script>
実際のメッセージ コードはテストしませんでした。これは単なるスケルトンであり、User
モデルを含む Rails アプリとtoken
、質問に答えるためだけに編集したくない (違反ではありません) 必要があるためです。