I never thought I would be writing an article on Medium, but I honestly couldn’t find a decent guide or example of using React Native with Socket.io for this use case. I did find some relevant examples, but they were either not descriptive enough or were using a different tech stack. So now it’s time for me to contribute to the wealth of knowledge.
Let’s dive right into it. First, a server and client need to be created. The example will be using an Express server and a plain React Native project. Once they are both created, they will both have to point to the same web socket which is how the data is transferred between the two.
Multiple sockets can be opened between a server and multiple clients. Socket.io makes it super simple to talk between a single client, many clients, or all the clients.
Once a socket is established, the two ends can speak freely and without delay (faster than HTTP requests 😊.).
To use the web socket, just send the data/message over a named channel.
socket.emit('channel-name', 'Hello world!');
This is identical for both server and client. The other end just has to listen to that named channel.
socket.on('channel-name', (message) => ... /* some logic */);
Simple data structures can be sent over the sockets too, so arrays and objects are fair game.
Back to our use case. When a user types and sends a message, it’ll be sent to the server, which can perform some logic, and then the server will emit the message to all sockets (other users). Messaging apps are expected to store data between sessions, so we’ll just save the message in the database while it’s being relayed.
The message model could be something like:
{text: String,createdAt: Date,userId: ObjectId,chatId: ObjectId}
To keep track of an open chatroom where any number of people can join, an identifier field will be helpful to keep track of the messages. For mobile apps, each device will act as a user and for new users, they will be assigned an id field which should then be kept in the device’s local storage. We can determine if a user has or has not joined the chatroom if there is an id field saved on the device. To deal with multiple chatrooms, some sort of mapping structure should be used so that we know which rooms that user is in if it does exist.
Regarding the persistence I mentioned earlier, when a user joins a room, we should give it any pre-existing messages that are saved in the database for that specific room.
I’ve created a working example of a working messaging app. Big thanks to Farid Safi for his messaging component which made this so much easier. Enjoy!
I’m a Computer Science student at Virginia Tech that loves to write code and lift weights 💪. LinkedIn Github