Skip to content

Instantly share code, notes, and snippets.

@SheptunovaAA
Created October 11, 2017 13:17
Show Gist options
  • Save SheptunovaAA/90b9cb9388420cd028aa5dab3d754252 to your computer and use it in GitHub Desktop.
Save SheptunovaAA/90b9cb9388420cd028aa5dab3d754252 to your computer and use it in GitHub Desktop.
kotlin example of OKHttp3 WSS
/**
don't forget to add in app gradle:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
and add INTERNET permission to AndroidManifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...>
<uses-permission android:name="android.permission.INTERNET" />
<application... />
/>
**/
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v7.app.AppCompatActivity
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import ru.biatech.apptemplate.R
import java.util.concurrent.TimeUnit
import okio.ByteString
class MainActivity : AppCompatActivity() {
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
message.setText(R.string.title_home)
return@OnNavigationItemSelectedListener true
}
R.id.navigation_dashboard -> {
message.setText(R.string.title_dashboard)
return@OnNavigationItemSelectedListener true
}
R.id.navigation_notifications -> {
message.setText(R.string.title_notifications)
return@OnNavigationItemSelectedListener true
}
}
false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
// wss test
val client = OkHttpClient.Builder()
.readTimeout(3, TimeUnit.SECONDS)
//.sslSocketFactory() - ? нужно ли его указывать дополнительно
.build()
val request = Request.Builder()
.url("wss://echo.websocket.org") // 'wss' - для защищенного канала
.build()
val wsListener = EchoWebSocketListener ()
val webSocket = client.newWebSocket(request, wsListener) // this provide to make 'Open ws connection'
}
}
private class EchoWebSocketListener : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
webSocket.send("Hello, it's SSaurel !")
webSocket.send("What's up ?")
webSocket.send(ByteString.decodeHex("deadbeef"))
webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye !")
}
override fun onMessage(webSocket: WebSocket?, text: String?) {
output("Receiving : " + text!!)
}
override fun onMessage(webSocket: WebSocket?, bytes: ByteString?) {
output("Receiving bytes : " + bytes!!.hex())
}
override fun onClosing(webSocket: WebSocket?, code: Int, reason: String?) {
webSocket!!.close(NORMAL_CLOSURE_STATUS, null)
output("Closing : $code / $reason")
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response) {
output("Error : " + t.message)
}
companion object {
private val NORMAL_CLOSURE_STATUS = 1000
}
private fun output(txt: String) {
Log.v("WSS", txt)
}
}
@SheptunovaAA
Copy link
Author

Alternative way - using of NV library

  • add to gradle:
    compile 'com.neovisionaries:nv-websocket-client:2.3'

And change code to next:
`override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)

    // just stupid rx to call WSS NOT(!) on MainThread
    Observable.just("Hello World")
            .subscribeOn(Schedulers.newThread())
            .observeOn(Schedulers.newThread())
            .subscribe({
                smth ->
                    testWSS() // !!! must be not on the MainThread
            })
}

private fun testWSS() {
    // Create a WebSocket with a socket connection timeout value.
    val ws = WebSocketFactory().createSocket("wss://echo.websocket.org", 5000)

    // Register a listener to receive WebSocket events.
    ws.addListener(object : WebSocketAdapter() {
        override fun onTextMessage(websocket: WebSocket?, text: String?) {
            super.onTextMessage(websocket, text)
            Log.v("WSS", text)
        }

        override fun onCloseFrame(websocket: WebSocket?, frame: WebSocketFrame?) {
            super.onCloseFrame(websocket, frame)
            Log.v("WSS", "closing socket")
        }
    })

    ws.connect()
    ws.sendText("hello !")
    ws.disconnect()
}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment