Receiving Messages From Laravel Echo Socket IO backend in Android Application

Zoran Šaško
The Startup
Published in
6 min readJul 21, 2020

Laravel framework provides very nice way of subscribing to channels and listening to events. In this article we will explore how we can receive broadcasted events from Laravel web app, in android application, using WebSockets.

Laravel Echo Web & Android App Sample

Article will be formed in two sections, first will describe Laravel web application setup and second section one will describe how we can integrate Socket IO in android application. If you are interested in android part of this article, you can skip web setup section. On the end of the article are the links to source code of both applications, so you can test the whole setup.

Laravel Web Application Setup

Main purpose of Laravel web application is to create/broadcast messages to available clients. In our web application we’ll use Redis broadcaster with Socket.IO server. In this section we’ll see all the steps required for Laravel web application to send broadcasted messages via WebSocket.

The Redis broadcaster will broadcast messages from our MessagesController (that we’ll create later) using pub/sub feature. We’ll pair it with a Socket IO server so we can receive messages from Redis and broadcast them to Socket IO channels.

So, the very first thing is to install Laravel Echo:

npm install --save laravel-echo

and Redis, via composer:

composer require predis/predis

Don’t forget to set Redis as broadcast driver in .env file:

BROADCAST_DRIVER=redis

And specify Redis properties:

REDIS_CLIENT=predis
REDIS_PREFIX=""

In the next step, we are going to pair Redis broadcaster with Socket.IO server. Because we want to receive send messages in web application (and also in android application), we’ll need to install appropriate Javascript library:

npm install — save socket.io-client

After installing Socket.IO Javascript client, we need to instantiate global Echo object with Socket.IO as broadcaster (in resources/js/bootstrap.js).

After specifying Echo object, we need to execute the following command in order to include it in our app.js, that we are going to use later in article, for listening of Echo events in our web app:

npm install
npm run dev

Now, we are very close to the finishing of Laravel dependencies configuration process. The very last thing is to install Socket.IO server. Because Laravel doesn’t get with Socket.IO server included, we’ll use community driven Socket.IO server: https://github.com/tlaverdure/laravel-echo-server

In order to install laravel-echo-server, we need to execute the following command:

npm install -g laravel-echo-server

After installing, we need to initialize laravel-echo-server, by executing the following command:

laravel-echo-server init

and when echo server configuration is done, we can start it by running the following command:

laravel-echo-server start

If server is successfully started, you’ll get the following output:

Laravel Echo Server running

By completing laravel-echo-server installation, we have preconfigured everything that is important on our Laravel web application side in order to send messages via Laravel Echo. So, in the next section we are going to make an controller that will send Laravel Echo messages.

Before creating an controller that will send our messages, let us explain a little bit how those messages can be sent.

Events that Laravel app will send are broadcasted over channels, which can be public or private. In our sample we’ll use public channel, but if you want to prevent from unauthorized users to listen for channel events, you can register private channel.

Let us create event called MessageCreated (in app/Events folder), that will be sent when we want to send Laravel Echo message to our subscribers (web app and android app):

In constructor, we are specifying message that will be sent to all the clients and broadcastOn method specifies channel name which will be receiving those messages.

The next step is to finally create our MessagesController that will use MessageCreated event, that we have created in previous step.

We should add route to method sendMessage() in web.php.

Route::post('messages', 'MessagesController@sendMessage');

In order to display a form to user where user can specify message that will be sent to clients, we need to make an appropriate view (messages.blade.php).

Our form consists of input field where user can write a message, submit button and container for received messages (since web application is also an client that can receive messages).

In messages view, we need to add some methods for listening Echo events and methods for sending messages:

First very important part of code listing from above is line

window.Echo.channel(‘messages’)

where our web application is listening for MessageCreated event in messages channel. Method postMessageToBackend() is executing asynchronous POST request and it creates new message broadcast. It’s invoked when user clicks on submit button.

Route to MessagesController, specified in web.php:

Route::get(‘messages’, ‘MessagesController@index’);

Now is the time for starting our web application:

php artisan serve

and by browsing the following url, we can see our messages form:

http://localhost:8000/messages

Here we are finished with simple Laravel Application, so we can start with Android application implementation.

Android Socket.IO Client Setup

Android application will establish connection with Laravel Echo server, receive broadcasted messages and display them on the screen.

Main screen will have simple layout, only one TextView that will show all received messages:

In order to make socket connection to our Laravel Echo server, we need to import appropriate library in android project:

implementation ‘com.github.MrBin99:LaravelEchoAndroid:1.03’

This library will allow us to connect to the socket server and to receive messages, sent from the server.

We are going to create BaseActivity, class that will be our base class containing all the required functionality for connecting to echo server:

In the code above, we can see that we have a few socket-related methods. Methods connectToSocket() and disconnectFromSocket() are methods that are responsible for connecting or disconnecting from WebSocket. Method listenForEvents() is method that is called after we have established successful socket connection and it main job is to ‘listen’ for events that are broadcasted from our socket backend.

In order to receive socket broadcast, we must specify the same ‘channel’ and ‘message’ as it’s defined in backend configuration. After we have received socket broadcast message, we have to parse it’s content. For that, we are using parseFrom() method from companion object, of MessageCreated class.

In order to parse received message, we are going to use Gson library, so we need to import it in our app/build.gradle file:

implementation ‘com.google.code.gson:gson:2.8.6’

We also need to add appropriate repository location from which this library will be fetched, in project level build.gradle file:

allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}

After we have created BaseSocketActivity, we can set our MainActivity to inherit BaseSocketActivity and call appropriate methods for establishing and destroying the socket connection:

Since cleartext HTTP traffic is not explicitly permitted, we need to specify that in network security configuration (res/xml/network_security_config.xml file):

and include this file as an application tag property of our manifest, like:

android:networkSecurityConfig="@xml/network_security_config"

Finally, don’t forget to set internet permission in manifest:

<uses-permission android:name="android.permission.INTERNET" />

Now you can test everything in android emulator. It’s important to specify socket backend url as:

http://10.0.2.2:6001

so we can connect to our Socket IO server on our local computer.

Congratulations, you can now test sending messages from web application to android application, using Laravel Echo.

Link to web/android application sample code:

PS: If you need cloud hosting solution, for hosting your Laravel app, I suggest to you DigitalOcean (affiliate link) since they aren’t too pricey and dashboard is very easy to use.

--

--