How to read from pubsub, send to browser through websocket?

Hi everyone,

I want to have a process subscribe to a pubsub topic, and when it gets a message from the topic, send that message across a websocket to a browser window (or processing or similar ). There is no information flow in the other direction. I think browser window will be easiest as I do not have to invent any protocols.

This seems like it should be simple? I’m not running a web app so I don’t want to make all of phoenix my dependency if I don’t have to. I saw three websocket libraries - websockex, cowboy websocket, and phoenix channel.

I’m going to write my own websocket message processor on the browser side that takes the messages and converts them into drwaings on the screen.

What’s the easiest way for an elixir newbie to do this? Something like:

defmodule Drawing
use WebSocket # for websockex

def start_link do 
  Pheonix.PubSub.subscribe :pubsub, "topic"
  WebSocket.start_link("https://localhost:4000/ws")  
  loop()
end 

def loop do 
  receive do 
    _ -> Websocket.send( .... ??? ) 
  end 
end 
end

Hi @vshesh,

The easiest way to do this as a newbie is to take the Phoenix dependency. It is designed to do this - see https://hexdocs.pm/phoenix/channels.html. It has everything you need to wire it up, tutorials, client side libraries, horizontal scaling etc.

Phoenix isn’t like a traditional web framework - you can just use the bits you want to. Plenty of people have built API only platforms using it (i.e. no web front end). This is an example drawing app (I haven’t looked closely) of a Phoenix backend and Elm front end - https://github.com/danbruder/whiteboard - it’s a little dated now, but should give you an idea.

1 Like