Build A Multi-User Chat Application Using Websockets

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.   

Step 1: Install Okhttp

Add dependency in build.gradle 

   ‘implementation ‘com.squareup.okhttp3:okhttp:4.2.2’

Step 2: Add Internet Permission

Add permission in manifest

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

Step 3: Write Code

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.

Kshitija Patil

Kshitija is an Android Developer having 3.5+ years of experience in Android Application Development and experience in providing Analysis, Design, Development, Testing, Maintenance & Enhancements. She always looks forward to learning new stuff.

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

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.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

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.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

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.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks
coma

Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.

author
George Hodulik
CEO, Stealth Startup, Ex-Google