SignalR Real-Time Communication (android application)
every day the call for real-time data syncing and monitoring becomes louder. it has been included in several approaches like weathering apps, dashboards, stocks, notes, chatting, and even more. one of these tools that help in building real-time applications is SignalR from Microsoft. it is not the best of course, but it has lots of features and customization that make its implementations easier than many other tools. also, since our backend servers mostly implemented in .net core by Microsoft also. so it will be easy-peasy the integration.
What is a real-time application?
it's the ability to have the server pushed data to the currently connected instantly, without the need to request a new version of the data from the clients. so, every time pushing a message/image/video/voice to the hub all other listeners will get notified of the content and they can update the UI with the new data.
What is SignalR?
ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data. SignalR also enables completely new types of web applications that require high-frequency updates from the server, for example, real-time gaming.
What is the Hub?
A Hub is a more high-level pipeline built upon the Connection API that allows your client and server to call methods on each other directly. SignalR handles the dispatching across machine boundaries as if by magic, allowing clients to call methods on the server as easily as local methods, and vice versa. Using the Hubs communication model will be familiar to developers who have used remote invocation APIs such as .NET Remoting. Using a Hub also allows you to pass strongly-typed parameters to methods, enabling model binding.
How do Hubs work?
When server-side code calls a method on the client, a packet is sent across the active transport that contains the name and parameters of the method to be called (when an object is sent as a method parameter, it is serialized using JSON). The client then matches the method name to methods defined in the client-side code. If there is a match, the client method will be executed using the deserialized parameter data.
Today, we are going to implement the client-side using the android platform with Kotlin and we will build a simple chat app. let’s dig into coding…
for setup, we are going to use SignalR v2.3, which is an older version but you can use the latest. i used this version too much time ago, i have uploaded the SDK here you can download it and import as usual lib in android.
using android studio 4.1.1, you will create a new project and import the lib. the imported lib will look like the below.
implementation project(path: ‘:signalr-client-sdk’)
sync, your project, and everything will be ready to go.
First, we need to set up the credentials for making a successful connection to the server that holds hubs.
val credentials =
Credentials { request ->
request.addHeader("Content-Type", "application/json")
}
var mHubConnection = HubConnection(
"${BuildConfig.BASE_URL}/signalr/hubs",
// signalr/hubs provided from backend side
"", true, ConsoleLogger()
)
mHubConnection?.credentials = credentials
mProxy = mHubConnection?.createHubProxy("HubName")
val clientTransport: ClientTransport = ServerSentEventsTransport(mHubConnection?.logger)
val signalRFuture = mHubConnection?.start(clientTransport)
signalRFuture?.get()
now, u started the connection. but, u still don’t know if it is established successfully or not! so, by adding the below code we will get notified once the connection is successful.
mHubConnection?.stateChanged { oldState, newState ->
Timber.d("stateChanged $oldState / $newState")
if (newState.equals(ConnectionState.Connected))//on success connection user shall be joining the room to start Chat
mProxy?.invoke(
String::class.java,
"Join",
JoinRequest(param1, param2)//authObject.like userid,roomId
)
?.done { Timber.d("Join $it") }
?.onError { Timber.d("Join ${it.localizedMessage}") }
}
so, the user will be notified once the connection is up and running then he will call the ‘Join’ method which expects an object of type JoinRequest. the JoinRequest normally contains info about the current user and the room he is going to join, some authentication fields as server-side expect!
third, the client must listen to the changes from the server and he also can send messages instantly.
the “appendText” is the method used from the server-side to listen to added messages. and “publishMessage” for sending a message with payload
// appendText called when some one send a message, so the message //will be delivered to both users via 'appendText'. this should be after you join the chat room.mProxy?.on("appendText", SubscriptionHandler1<MessageResponse> {
Timber.d("displayText ${it.Message}")
}, MessageResponse::class.java)// when a user wants to send a message to other user/s we use 'publishMessage' to deliver the message to others. mProxy?.invoke(
"publishMessage",
MessageRequest(
senderId,
message
)
)
finally, don’t forget to load the old messages using a remote API for retrieving them.
we have done with implementation as a piece of cake!
Hope this will work for you! if so, share and invite friends.
Clapp is appreciated -_*