Rails 5 + ActionCableで作る!シンプルなチャットアプリ(DHH氏のデモ動画より) - QiitaでできるチャットサーバにWebSocketクライアントで接続したかったのでひとまずRubyでやってみた。
よく内容を理解しないまま出来てしまったがとりあえずメモしておく。
参照サイト
ActionCableをwebsocket APIとして使ってUnityと通信する - Qiita
ruby on rails - Connecting to ActionCable from iOS app - Stack Overflow
とりあえずできた
require 'websocket-client-simple'
require 'json'
ws = WebSocket::Client::Simple.connect 'ws://localhost:3000/cable'
ws.on :message do |msg|
puts msg.data
end
ws.on :open do
id = { channel: 'RoomChannel' }
# channel参加(on :messageでメッセージを受け取れるように)
ws.send({ command: 'subscribe', identifier: {channel:'RoomChannel'}.to_json}.to_json)
# channel参加完了前にメッセージを送るとエラーとなるのでとりあえず
sleep 1
# メッセージ送信
ws.send({ command: 'message', data: {message: 'hogemogeaa2', action: 'speak'}.to_json, identifier: {channel:'RoomChannel'}.to_json}.to_json)
end
ws.on :close do |e|
exit 1
end
loop do
ws.send STDIN.gets.strip
end