Build

Java WebSocket Programming with Android and Spring Boot

6 min read Markus Kohler on Jan 15, 2024

The WebSocket protocol provides an always-on connection between a client and a server for bi-directional communication. This is great for applications that require a real-time connection, such as multiplayer gamesinternet of things applications, and chat apps. The use case for this tutorial is a chat application, a classic example of real-time communication. In this tutorial, we are going to set up a simple Android client that will connect to a WebSocket server using Spring Boot.

Java WebSocket Client

For the Android client, we are going to make a simple demo app that contains four image buttons of cute animals. Before diving into the Java implementation it is worth noting that Kotlin has become a popular choice for Android development. To get started, initialize a new project on Android Studio, with a Basic Activity, called JavaWebSocketClient. We are going to use a lightweight WebSocket client library for the app, which can be found in this GitHub repo. In order to use this library, we have to add it to the build.gradle file in the app directory. Add the following to the dependencies and sync the project:

Make sure to include the internet access permission in the manifest file:

Connect the Client to the Server

Go to MainActivity.java, import the following packages and set up onCreate():

Next, create a new method createWebSocketClient():

This may look like a lot, but really, we are doing four key things in this method:

  1. Starting a new WebSocket connection to the localhost “ws://10.0.2.2:8080/websocket”.

  2. Sending a message to the server once a connection is opened.

  3. Displaying the messages sent from the server on the app.

  4. Setting timeouts and automatic reconnection.

Now that we connected the client to the server, let’s set up the method to send messages to the server.

Send Messages to the Server

In MainActivity.java, add the following to sendMessage():

When a button is pressed, the button id is sent to the server. This method is called from the file animal_sounds.xml, which you can get from my Java WebSocket Programming Repo. Make sure to modify the file strings.xml under the values directory so you won’t get any errors in the XML file.

The last thing to do on the client-side is to add the images for the animals in the drawable directory. The images are made by Freepik from www.flaticon.com.

Run the Android app in your emulator:

Nothing happens right now because the server is not set up. Let’s do that right now!

Spring Boot WebSocket Server

For our server, we will use Spring Boot which makes it easy to create production-grade Spring applications with minimum configurations. To quickly bootstrap our project, we will use Spring Initializr. We will generate a Gradle project, but you can also generate a Maven project if you prefer. Configure the Initializr like the screenshot below and make sure to add WebSocket as a dependency:

Generate the project to download a zip file. Once you unzip the file, go to the src directory and keep on clicking the subdirectories until you get to the JavaWebSocketServerApplication.java file.

Add two files to the directory WebSocketHandler.java and WebSocketConfiguration.java.

Handle the WebSocket Messages

We have to handle the incoming messages that arrive in the server. To do so, in WebSocketHandler.java inherit the class to implement the method handleTextMessage(). Add the following code to the file:

Inside the method, we simply get the string value of the message payload and do a switch expression to check the value of the message with the value of each case. A unique message with the animal sound is sent to the client.

Configure the WebSocket Request Handling

In WebSocketConfiguration.java, implement the interface WebSocketConfigurer and add the following code to the file:

We set up the method registerWebSocketHandlers to configure the WebSocketHandler to the path “/websocket“. That is all for the server-side. Now that we have everything set up, let’s start the WebSocket server and run the app!

Send Data between Server and Client

In the terminal, go to the root directory of your Spring Boot project and run the following command to start the server:

Next, run the Android client in Android Studio, and once the app loads, click any of the four buttons.

Play around with the Android app and see how messages are sent from client to server with WebSockets!

Update the Android Client to Pub/Sub

Sending data client-to-server or server-to-client is not difficult and can be done pretty fast. But what if you want to send data client-to-client? You can’t directly connect clients without implementing some routing and message broker logic (via enableSimpleBroker and registering it with MessageBrokerRegistry type) on the server.

Talk to an Expert

Let's connect to discuss your real-time project.

By submitting this form, you are agreeing to our Terms and Conditions and Privacy Policy.

There are several tools we can use to make this task less time-consuming. One such tool is Socket.IO, which sets up a real-time, bidirectional connection between clients. This is a great open-source tool to use, but we still need to set up a server and connect the client to the server. Another such tool is to use subprotocols like STOMP in Spring Boot to embed STOMP messages. This subprotocol operates on top of WebSocket and enables WebSocket message handling. However, you also have to set up the endpoints yourself using the StompEndpointRegistry type and then add the endpoints with the addEndPoint method. Is there an easier way to securely and reliably send data between clients without manually setting up a server? With PubNub, we can.

PubNub provides the real-time infrastructure to power any device that speaks TCP. We can stream data from client-to-client, client-to-server, or server-to-client using PubNub’s Global Data Stream Network in under 100 ms! With PubNub, an always-on connection is made between the devices connected to the channel, similar to WebSockets. The best part is that you don’t have to worry about setting up a backend server and maintaining the server because PubNub is serverless and infinitely scalable.

To see how PubNub simplifies the process of sending data from client-to-client, we will modify the Android app we built earlier. But first, sign up for a free PubNub account to get your free Pub/Sub API keys.

Modify the Android Client

To differentiate the updated app from the old app, create a new Android project called PubNubJavaClient. In order to use PubNub’s Android SDK, update the json by adding the following to the build.gradle file in the app directory and sync the project:

Include the following permissions to the manifest file:

Everything else, except MainActivity.java, is the same. From the previous app, add the following files to the updated app:  animal_sounds.xmlstrings.xml and the images from the drawable directory. Once you finish this, go to MainActivity.java to add the new code. Import the following packages and set up onCreate():

Make a call to initPubNub() to initialize PubNub:

We do three key things in this method:

  1. Initialize the PubNub client API. Make sure to replace “ENTER_YOUR_PUB_KEY” and “ENTER_YOUR_SUB_KEY” with your Pub/Sub keys.

  2. Set up a listener to get notified of messages that arrive on the channel. As we did earlier, display the message on the app for the client to see.

  3. Subscribe to the global channel where messages will be published.

When the user presses a button, the method sendMessage() is called:

This method is similar to what we did earlier, except now we publish the actual message, the animal sound, to the global channel and not the server. We use publishMessage() as a helper function to publish the message.

That is all we need to get the app up and running!

Send Data Between Clients

Run the Android app in two emulators to see messages appear in real time.

Note: To ensure seamless communication between clients, make sure both the Android emulators have the same PubNub keys and are subscribed to the same channel. This is crucial for establishing a successful WebSocket connection for real-time communication.

Now that you've learned how to send data using WebSockets in Java, don't forget to explore our other resources.

Lastly, check out our docs to learn about additional features that PubNub offers such as Message ActionsObjects, and Signal messages to give your application a robust edge. Check out our updated screenshots and resource links for a more comprehensive understanding.

With PubNub, you can also create solutions tailored for geolocationedge message busenterprise softwaregamingdigital health, and ecommerce.

To get started, you might want to check our general setup guide, which will walk you through setting up your account. If you're interested in learning how to send and receive messages, we have guides for that too. Check out our send messages guide and receive messages guide for more information.

For more advanced functionalities, such as sending messages, message receipts, and unread counts in a chat scenario, you may refer to these documents: sending messagesmessage receipts, and unread counts.

If you're working on an Android platform and want to implement push notifications, we've got you covered. Visit our Android push guide and send push guide for detailed instructions on how to set up push notifications with firebase and PubNub.

Have suggestions or questions about the content of this post? Reach out to devrel@pubnub.com.