Setting up Message Transmission

eunjoon.hwang
Building Couch Potato
3 min readJun 18, 2020

Our biggest challenge to socket.io configurations for Couch Potato, a Chrome extension allowing users to watch shows together on Hulu from the comfort of their own couch, was to emit messages only to users in the room (in our case, we call it a couch). Let’s say users A, B, C are on the couch one, D, E is on the couch two, we don’t want a message sent to A from B would be broadcasted into room two to user D, E.

Fortunately, socket.io has Room support. Socket.io allows you to namespace your sockets, which essentially means assigning different endpoints or path. This is a useful feature to minimize the number of resources (TCP connections) and, at the same time, separate concerns within your application by introducing a separation between communication channels. Within each namespace, you can also define arbitrary channels that socket can join and leave.

This image illustrates how namespaces, rooms, and sockets are divided. The room is defined as arbitrary channels that sockets can join to subscribe the socket to a given channel:

And then simply use to or in when broadcasting or emitting:

To leave a channel, you call leave in the same as join. Both methods are asynchronous and accept a callback argument.

Then how is the Socket is identified? Each Socket in socket.io is identified by random unique identifier Socket#id and automatically joins a room designated by its own id (in our case, we generate couchID).

This makes it easy to broadcast messages to other sockets:

Now, we have enough information to write our backend for socket transmissions. Let’s look at how we implement connections and send-chat-message via sockets.

Connection to a room (couch) seems straight forward. But how about the “send-chat-message,” we establish another “receive-message” io.in(couch) inside of the send-chat-message to be associated with the user. Finally, we can send chat messages with user information (such as username, avatar, couch) and receive all the messages from other users on the couch.

Stay tuned in our next post as we are discussing how and why we decided to and convert the chat app to React

Interested in learning more about Couch Potato? Start this blog series from the beginning! And don’t forget to download Couch Potato from the Chrome store so you can start watching shows with friends now!

--

--