Skip to content
Daniel Rees edited this page Jun 21, 2019 · 2 revisions

Basic Usage

Connecting to a Socket and joining Channels is pretty straight forward.

// MainActivity.ktfunconnectToChatRoom() {
// Create the Socketval params = hashMapOf("token" to "abc123")
val socket =Socket("http://localhost:4000/socket", params)
// Listen to events on the Socket
socket.onOpen { addTextToView("Socket Opened") }
socket.onClose { addTextToView("Socket Closed" }
socket.onError { throwable, response ->Log.d(throwable, "TAG", "Socket Error ${response?.code}") }
// Join channels and listen to events
channel.on("join") { this.addTextToView("You joined the room") }
channel
.join()
.receive("ok") { addTextToView("Joined Channel") }
.receive("error") { addTextToView("Failed to join channel: ${it.payload}") }
// You can call `connect()` before or after creating and joining channels
socket.connect()
}
funaddTextToView(text:String) {
runOnUiThread { // Note the changing of threads// A RecyclerView Adapter that manages a list of text on the devicethis.messageAdapter.add(text)
}
}

Note on Asynchronous Behavior

The client does not perform work on the calling thread, however callbacks are not guaranteed to be delivered on the calling (or main) thread. Therefore, you will need to switch to the uiThread in order update the view

Customizing the Socket

OkHttp

If you have a custom OkHttpClient configuration, you can provide it when creating the Socket

val customClient =OkHttpClient.Builder()
.addInterceptor(myInterceptor)
.connectTimeout(1000, TimeUnit.MILLISECONDS)
.build()
val socket =Socket(url ="http://localhost:4000/socket/websocket",
client = customClient)

Socket Defaults

You can change some of the defaults of the Socket

val socket =Socket("http://localhost:4000/socket/websocket")
/** Timeout to use when opening a connection or joining a Channel */
socket.timeout =5_000// in ms/** Interval between sending a heartbeat, in ms */
socket.heartbeatIntervalMs =15_000/** Interval between socket reconnect attempts, in ms */
socket.reconnectAfterMs = { tries ->if (tries >2) 100LelselistOf(10L, 50L)[tries -1] }
/** Interval between channel rejoin attempts, in ms */
socket.rejoinAfterMs = { tries ->if (tries >2) 5_000LelselistOf(1_000L, 2_000L)[tries -1] }
/** Disables heartbeats from being sent. Default is false. */
socket.skipHeartbeat =true

Logging

To receive logs, simply add a logger method to the Socket

val socket =Socket("http://localhost:4000/socket/websocket")
socket.logger = { message ->Log.d(TAG, message) }

Clone this wiki locally