LoginSignup
5
9

More than 5 years have passed since last update.

ActionCableにRubyのWebSocketクライアントで接続してみる

Posted at

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
5
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
9