Websocket is the two-way communication protocol to send and receive the data between client and server.
It operates over HTTP through TCP/IP socket connection. It is used for passing the message between client and server.
We can Build a multi-user chat application using WebSockets.
To connect the client with the server, we have created a WebSocketManger class.
OkHttpClient is used for connection purpose.
Add dependency in build.gradle
‘implementation ‘com.squareup.okhttp3:okhttp:4.2.2’
Add permission in manifest
<uses-permission android:name=”android.permission.INTERNET”/>
OkHttpClient is used to send an HTTP request. For authentication purposes, we have used a header with the url using an access token.
fun init(url: String, _messageListener: MessageListener) {
client = OkHttpClient.Builder()
.build()
request = Request.Builder().url(url).addHeader(
"Authorization", "Bearer " + ACCESS_TOKEN).build()
messageListener = _messageListener
}
The next is to connect the url through a web socket where we used the OkHttpClient new WebSocket use request to connect a new web socket. We will call the connect function after the above method is called.
Here createlistener is a function of websocketlistener.
fun connect() { if (isConnect()) { return } client.newWebSocket(request, createListener()) }
To reconnect the websocket we have also created a reconnect function by checking if it is already connected or not.
fun reconnect() {
if (connectNum <= MAX_NUM) {
try {
Thread.sleep(MILLIS.toLong())
connect()
connectNum++
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
}
fun isConnect(): Boolean {
return isConnect
}
These are the functions used to send messages to the client through the server. The ‘send’ function is used. Most importantly, we need to have a message format so that we can connect, send and receive the data; otherwise, the socket disconnects automatically. We have to predefine the send message format to share the data between the clients and server.
fun sendMessage(text: String): Boolean {
return if (!isConnect()) false else mWebSocket.send(text)
}
fun sendMessage(byteString: ByteString): Boolean {
return if (!isConnect()) false else mWebSocket.send(byteString)
}
This function is used to close the connection between the sockets. To avoid any issues, we will be checking whether the WebSocket is connected or not.
cancel() method is invoked immediately and violently releases resources held by this web socket, discarding any enqueued messages. This does nothing if the web socket has already been closed or canceled.
fun close() { if (isConnect()) { mWebSocket.cancel() mWebSocket.close(1001, "to close socket") } }
WebSocket messages are handled by the interface .i.e WebSocketListener. It has the function which performs accordingly to the event called. An instance of the lifecycle is managed.
onOpen method is to be invoked when a WebSocket has been accepted by the remote peer and may begin transmitting messages.
onMessage method is invoked when the WebSocket has received the messages.
There are two onMessage methods one is to receive the message in string format, and the other is to receive the message in byteString format.
onClosing method is invoked to close the connection between the client and the server.
onFailure method is invoked when the connection fails between the client and the server.
private fun createListener(): WebSocketListener { return object : WebSocketListener() { override fun onOpen( webSocket: WebSocket, response: Response ) { super.onOpen(webSocket, response) mWebSocket = webSocket isConnect = response.code == 101 if (!isConnect) { reconnect() } else { messageListener.onConnectSuccess() } } override fun onMessage(webSocket: WebSocket, text: String) { super.onMessage(webSocket, text) messageListener.onMessage(text) } override fun onMessage(webSocket: WebSocket, bytes: ByteString) { super.onMessage(webSocket, bytes) messageListener.onMessage(bytes.base64()) } override fun onClosing( webSocket: WebSocket, code: Int, reason: String ) { super.onClosing(webSocket, code, reason) isConnect = false messageListener.onClose() } override fun onClosed( webSocket: WebSocket, code: Int, reason: String ) { super.onClosed(webSocket, code, reason) isConnect = false messageListener.onClose() } override fun onFailure( webSocket: WebSocket, t: Throwable, response: Response? ) { super.onFailure(webSocket, t, response) if (response != null) { isConnect = false messageListener.onConnectFailed() messageListener.onClose() } } } }
Here is the full code for WebSocket manager
object WebSocketManager { private val TAG = WebSocketManager::class.java.simpleName private const val MAX_NUM = 5 private const val MILLIS = 5000 private lateinit var client: OkHttpClient private lateinit var request: Request private lateinit var messageListener: MessageListener private lateinit var mWebSocket: WebSocket private var isConnect = false private var connectNum = 0 fun init(url: String, _messageListener: MessageListener) { client = OkHttpClient.Builder() .build() request = Request.Builder().url(url).addHeader( "Authorization", "Bearer " + ACCESS_TOKEN ).build() messageListener = _messageListener } fun connect() { if (isConnect()) { return } client.newWebSocket(request, createListener()) // client.dispatcher.executorService.shutdown() } fun reconnect() { if (connectNum <= MAX_NUM) { try { Thread.sleep(MILLIS.toLong()) connect() connectNum++ } catch (e: InterruptedException) { e.printStackTrace() } } } fun isConnect(): Boolean { return isConnect } fun sendMessage(text: String): Boolean { return if (!isConnect()) false else mWebSocket.send(text) } fun sendMessage(byteString: ByteString): Boolean { return if (!isConnect()) false else mWebSocket.send(byteString) } fun close() { if (isConnect()) { mWebSocket.cancel() mWebSocket.close(1001, "to close socket") } } private fun createListener(): WebSocketListener { return object : WebSocketListener() { override fun onOpen( webSocket: WebSocket, response: Response ) { super.onOpen(webSocket, response) mWebSocket = webSocket isConnect = response.code == 101 if (!isConnect) { reconnect() } else { logE(TAG, "connect success.") messageListener.onConnectSuccess() } } override fun onMessage(webSocket: WebSocket, text: String) { super.onMessage(webSocket, text) messageListener.onMessage(text) } override fun onMessage(webSocket: WebSocket, bytes: ByteString) { super.onMessage(webSocket, bytes) messageListener.onMessage(bytes.base64()) } override fun onClosing( webSocket: WebSocket, code: Int, reason: String ) { super.onClosing(webSocket, code, reason) isConnect = false messageListener.onClose() } override fun onClosed( webSocket: WebSocket, code: Int, reason: String ) { super.onClosed(webSocket, code, reason) isConnect = false messageListener.onClose() } override fun onFailure( webSocket: WebSocket, t: Throwable, response: Response? ) { super.onFailure(webSocket, t, response) if (response != null) { // "connect failed “ ) isConnect = false messageListener.onConnectFailed() messageListener.onClose() } } } }
Below are the example of how to initiate the WebSocket with the init method followed by the connect method
WebSocketManager.init(“$CHAT_SERVER_URL”}”, this)
WebSocketManager.connect()
To send the message to the client after we receive a success message on connection, invoke the send message method with the proper format already defined at the server side to transfer the data.
WebSocketManager.sendMessage(text)
When the operation is complete, we can call the close method.
WebSocketManager.close()
This is the simplest and easiest way to communicate with the client and server to transfer the data using WebSocket.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowWe had very close go live timeline and MindBowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Our CISO was extremely impressed by Mindbowser’s work. It is pretty rare to see this kind of clean security report so early in the company’s journey. Huge Thank you for the disciplined approach here.
Founder, TrestleIQ
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
The flexibility and capacity of the Mindbower staff has been impressive.
CEO, ProofPilot
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.
Founder, Courtyardly
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork
We cannot express enough how pleased we are with the entire Mindbowser team. From our first call, they focused on our vision and ensured things were handled as per requirement. Communication was so easy and flexible to our schedule. I’m...
Founder, SafeZone Safety Systems