Lee Eather
Lee Eather

Reputation: 355

Broadcasted message will not show up in browser console after being sent, actioncable and redis development env

I have got redis setup for windows running the server from redis cli

C:\program files\redis>redis-cli
127.0.0.1:6379>

Development cable.yml is

development:
  adapter: redis
  url: redis://127.0.0.1:6379/0

Notifications channel rb

class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_from "notifications_#{current_user.id}"
  end
end

Start rails server and load up the page, server prints

Started GET "/cable/" [WebSocket] for ::1 at 2018-09-29 13:07:17 +1000
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: keep-alive, Upgrade, HTTP_UPGRADE: websocket)
Registered connection (Z2lkOi8vcGVvcGxlcy9Vc2VyLzUwMQ)
NotificationsChannel is transmitting the subscription confirmation
NotificationsChannel is streaming from notifications_501

notifications.js on page is

App.notifications = App.cable.subscriptions.create("NotificationsChannel", {
  connected:  function() {
    alert("hello")
  },
  recieved: function(data) {
    console.log(data)
  }
});

Alert pops up saying is connected on page load. In another terminal run rails console

irb> ActionCable.server.broadcast("notifications_501", body: "hello")

Look back in rails server output

NotificationsChannel transmitting {"body"=>"hello"} (via streamed from notifications_501)

But the console doesnt show the JSON object?

** Edit **

Creat another instance of redis server

C:\program files\redis>redi-cli
127.0.0.1:6379>subscribe "notifications_501"
1)"subscribe"
2)"notifications_501"
3)(integer) 1

Open another cli

127.0.0.1:6379>publish "notifications_502" "{\"body\":\"hello\"}"

It transmits to both the rails server and the subscribed redis server

NotificationsChannel transmitting {"body"=>"hello"} (via streamed from notifications_501)

Upvotes: 0

Views: 244

Answers (2)

John Baker
John Baker

Reputation: 2398

I think the reason it didn't work for you on your first try might be because of a typo when naming received function. You did recieved instead.

Upvotes: 1

Lee Eather
Lee Eather

Reputation: 355

Change notifications.js to notfications.coffee and have code like this

App.notificationss = App.cable.subscriptions.create "NotificationsChannel",
  connected: ->
  # Called when the subscription is ready for use on the server

  disconnected: ->
  # Called when the subscription has been terminated by the server

  received: (data) ->
    alert("hello")
  # Called when there's incoming data on the websocket for this channel

Not sure why normal javascript is not working..

Upvotes: 0

Related Questions