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.

Keep Reading

Keep Reading

Struggling with EHR integration? Learn about next-gen solutions in our upcoming webinar on Mar 6, at 11 AM EST.

Register Now

Let's create something together!