Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use socket IO in kotlin?

I want to initialize socket IO in my kotlin app.

my problem is here :

    private var mSocket: Socket? = null
{
    try {
        mSocket = IO.socket("http://chat.socket.io")
    } catch (URISyntaxException e) {
    }
}

import com.github.nkzawa.socketio.client.IO

cant recognize

like image 758
SadeQ digitALLife Avatar asked Nov 07 '22 05:11

SadeQ digitALLife


1 Answers

I searched for this some more and found this solution:

You connect your ws like this:

val opts = IO.Options()
opts.path = "/path/to/ws"
opts.transports = arrayOf(WebSocket.NAME) // Set the transfer to 'websocket' instead of 'polling'
val webSocket = IO.socket("http(s)://your.ip.here", opts)
webSocket.connect()
    .on(Socket.EVENT_CONNECT) {
         // Do your stuff here
    }
    .on("foo") { parameters -> // do something on recieving a 'foo' event
         // 'parameters' is an Array of all parameters you sent
         // Do your stuff here
     }

If you want to emit an event, you'll call:

webSocket.emit("foo", "bar") // Emits a 'foo' event with 'bar' as a parameter

You will need to use

import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;

so be sure to add the corresponding libraries to your build.gradle

dependencies {
    ...
    implementation 'com.github.nkzawa:socket.io-client:0.6.0'
}
like image 107
DreamyLynn Avatar answered Jan 01 '23 20:01

DreamyLynn