Skip to content

Instantly share code, notes, and snippets.

@talum
Created September 13, 2017 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save talum/2fd5699a772adf6014c28fdba0fae9f4 to your computer and use it in GitHub Desktop.
Save talum/2fd5699a772adf6014c28fdba0fae9f4 to your computer and use it in GitHub Desktop.
programming phoenix ch 10

Programming Phoenix: Chapter 10 Channels

Channel

  • single client on page connects directly with a process on the server called a channel
  • cilents & servers talk directly to each other
  • channel sends, receives, message aand keeps state
  • messages are events
  • state is in a struct called socket
  • phoenix conversation is about a topic
  • each user's conversation on a topic has its own isolated, dedicated process

Phoenix Clients with ES6

  • topic allows us to send events to tohers interested in the same topic
  • topics are strings that serve as identifiers e.g. topic:subtopic \ resource:identifier
  • client establishes new connection with socket
  • socket will be transformed through life of connection
  • socket is the ongoing conversation between client and server

UserSocket

  • UserSocket starting point for all socket connections
  • UserSocket uses a single connection to server to handle all channel processes
  • two functions: connect and id to determine if someone canc onnect and how to identify the socket

Creating the Channel

  • topic ids allow us to scope channel connections

  • when users join a channel, they must provide a topic

  • sockets hold all of state for given conversation

  • for channels, socket ist ransformed in loop rather than single pipeline (180)

  • handle_in receives direct channel events

  • handle_out intercepts broadcast events

  • handle_info receives OTP messages

  • broadcast! function sends an event to all users on the current topic

  • broadcast! takes three arguments, the socket, the name of the event, and a payload

Socket Authentication

  • token authentication works better for sockets b/c connection is long-duration and they don't rely on a specific transport
  • when to reply and when not to?
  • "It's common practice to acknowledge the result of pushed messages from the client. This approach allows the client to easily implement UI features such as loading statuses and error notifications"

Handling Disconnects

  • stateful convo must handle data that gets out of sync
  • disconnects can be caused by server restart, internet disconnect, bad connection, broadcast not received when client is away
  • track a last-seen_id on the client
  • rejoins after crash or disconnect send last_seen_id
  • channel on the client holds a params object and sends it to the server every time we call channel.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment