How do I subscribe a socket to a Phoenix Channel from the server side? (rather than the client side)

I’m using Phoenix Channels to create an endpoint to be consumed by vanilla websockets (without client library).

To simplify things, I want to automatically join the user’s socket to various channels on connect.

Currently, the only way I can see to do it is if the client sends a phx_join message; it doesn’t seem possible to do it from the server.

I’m looking for something of the form socket = subscribe(socket, room).

What am I doing wrong?

1 Like

Well the default socket implementation is not meant to by vanilla websockets. You will have to implement your websocket by implementing the Phoenix.Socket.Transport behaviour.

It doesn’t seem to be a problem connecting with vanilla websocket (it works fine)? The also doesn’t really affect the issue, which is the case of auto-joining channels.

I know you can join multiple channels from a base channel see here, but I am not sure that you can do it directly from the socket code.

You’re connecting to the websocket endpoint, but unlikely to channels. Phoenix channels are not plain websockets, but a communication protocol, which can run on top of websockets, but also other transports.

So you need to implement that communication protocol for your plain websocket client. You can e.g. look at GitHub - mobileoverlord/phoenix_client: Elixir Phoenix Client for Channels for a pure elixir implementation of connection to phoenix channels.

1 Like

Hey Ben! Yes, I totally agree with you. The good news is that it’s just a simple JSON layer on-top of websockets; I was able to knock up join functionality etc with Python in just a few lines.

The issue here isn’t the actual communication bit, but getting the phx_join message to come from the server rather than the client.

I had a go with this but adapting it to the Socket. Alas it was just as you said, no luck. Thank you though, that’s easily the closest I’ve come to solving the issue! :slight_smile:

1 Like

I guess you would have to port the phoenix.js library to python. It is a very tiny client, simple and straightforward so it is worth a try and let it handle phx_join :slight_smile:

Oh I definitely can port it to Python (I already kind-of have, in about 20 lines!).

The idea is just for the client to be able to subscribe to messages from the server (one-way).

I think I might try and write my own socket that hooks into PubSub in background, and delivers a simplified websocket interface. That’s tomorrow’s challenge :wink:

May be you can use Erlang – gen_tcp
@chrism2671