Websocket Flashcards
What is WebSocket? And why do we need it?
WebSockets are a protocol built on top of TCP ( As HTTP for example) . They hold the connection to the server open so that the server can send information to the client, even in the absence of a request from the client. WebSockets allow for bi-directional, “full-duplex” communication between the client and the server by creating a persistent connection between the two.
What is Connection?
A place for authorizing connection.
What is Channel?
A place for common logic between channels.
How to generate new channel?
rails g channel channel_name
How to broadcast event?
ActionCable.server.broadcast “channel_name”, {}
What files creates rails channel generator?
# app/channels/animals_channel.rb class AnimalsChannel < ApplicationCable::Channel def subscribed # stream_from "some_channel" end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
app/javascript/channels/animals_channel.js
consumer.subscriptions.create("AnimalsChannel", { 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) { // Called when there's incoming data on the websocket for this channel } });
What files creates rails channel generator? ( 2 files and 5 methods)
# app/channels/animals_channel.rb class AnimalsChannel < ApplicationCable::Channel def subscribed # stream_from "some_channel" end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
app/javascript/channels/animals_channel.js
consumer.subscriptions.create("AnimalsChannel", { 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) { // Called when there's incoming data on the websocket for this channel } });
How to create a stream subscription?
def subscribed
stream_from “sample”
end
What are the main elements to create websocket event? ( 5 things)
1) Button
2) Action inside controller
3) Event which we run from action
4) A subscription that catch this event
5) JS that show the result on every page