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 NowMaster Epic Integration with SMART on FHIR in Just 60 Minutes
Register HereMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We 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
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
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
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