Dynamic Topics
Let's dive into the details of dynamic topics and their role in Channels.
Topics
Topics are string identifiers used to connect to the correct Channel when the phx_join
message is received by the Socket. They are defined in the Socket module, as we previously saw with our UserSocket
example.
# hello_sockets/lib/hello_sockets_web/channels/user_socket.exchannel "ping", HelloSocketsWeb.PingChannel
A topic can be any string, but it is best to use a topic:subtopic
format for the topic name. This convention allows us to have a single Socket module with different Channels associated with it. This is because channel/3
can accept a wildcard splat operator as the final part of the string.
Let’s change our topic definitions to use a wildcard operator and then observe the effects:
# hello_sockets/lib/hello_sockets_web/channels/user_socket.exchannel "ping", HelloSocketsWeb.PingChannelchannel "ping:*", HelloSocketsWeb.PingChannel
We can then connect to a ping:wild
Channel and send messages to it.
wscat -c 'ws://localhost:4000/socket/websocket?vsn=2.0.0'connected (press CTRL+C to quit)> ["1","1","ping:wild","phx_join",{}]< ["1","1","ping:wild","phx_reply",{"response":{},"status":"ok"}]> ["1","1","ping:wild","ping",{}]< ["1","1","ping:wild","phx_reply",{"response":{"ping":"pong"},"status":"ok"}]
It’s possible to use the topic of *
to allow any topic to route to the Channel. Any routing is permitted as long as the *
...