Chat app from scratch with React Native and Java (Part 2 — backend)

Tomas Zaicevas
2 min readAug 2, 2020

In part 1 we developed a front-end part of our little chat app. In this part, we will write the backend. Full source code: https://github.com/zaicevas/chat-demo

Let’s start by finishing the frontend, so that it’s ready to receive messages from the backend. We will do it in two phases:

  • Writing a WebSocket wrapper
  • Using the wrapper in our App component

Writing a WebSocket wrapper

The reason we’re doing it, is to have the logic, concerned with how to send and receive messages to a server, be outside of the UI component.

Create a WebSocketClient.js:

Note, that in 30th line, you need to pass your local IP. Sadly, localhost won’t work, because of iOS restrictions.

Using the wrapper in our App component

Let’s update our App.js so that it uses our WebSocketClient to retrieve and send messages:

The tricky part here is the second useEffect. This useEffect runs every time messages change. It’s not enough call that useEffect once, because in that case, messages would not refer to the latest state. That problem could also be solved with other techniques (for instance, useRef) but this solution seems simpler and sufficient.

After these changes, we are ready to send and receive new messages from our backend server.

Building the backend

Let’s go straight to spring initialzr and choose following options:

Note: this screenshot was taken a while back, the page might look differently by now, including versions.

When the project is generated, hop into your favourite IDE and let’s add a couple of dependencies into our pom.xml. At the end, it should look like this:

Let’s then create a class which will handle WebSocket messages

We need another class, which maps our WebSocket API path and the handler.

Congratulations for making it that far, because we have only one thing left — implement our WebSocketHandler:

In a nutshell, we’re taking every message that we receive and send it to all of the clients. Simple, isn’t it?

Now you should be able to connect to the app with two or more phones and chat!

Chat

This app, of course, has gazillion number of problems, some of which are:

  1. What about users with the same name?
  2. No persistence
  3. No auth

However, I am going to let you solve them on your own! Thank you for following these tutorials. You can find the source code here: https://github.com/zaicevas/chat-demo

--

--