Created
March 26, 2020 23:52
-
-
Save emedinaa/4e3fa0baab7bbb20684b8476776ffc80 to your computer and use it in GitHub Desktop.
Socket IO + android + kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
socketio='1.0.0'//‘io.socket:socket.io-client:1.0.0' https://mvnrepository.com/artifact/io.socket/socket.io-client/1.0.0 | |
implementation "io.socket:socket.io-client:$rootProject.socketio" | |
package com.emedinaa.kotlinapp.data.socket | |
import io.socket.client.Ack | |
import io.socket.emitter.Emitter | |
import androidx.annotation.Nullable | |
import io.socket.client.IO | |
import io.socket.client.Socket | |
import java.net.URISyntaxException | |
class SocketManager { | |
private var mSocket: Socket? = null | |
init { | |
//val opts = IO.Options() | |
try { | |
mSocket = IO.socket("https://my-url/") | |
} catch (e: URISyntaxException) { | |
throw RuntimeException(e) | |
} | |
} | |
private fun on(event: String, listener: Emitter.Listener) { | |
mSocket?.on(event, listener) | |
} | |
private fun emit(event: String, @Nullable obj: Any, @Nullable ack: Ack) { | |
mSocket?.emit(event, obj, ack) | |
} | |
fun removeEvent(event: String) { | |
mSocket?.off(event) | |
} | |
fun connect(listener: Emitter.Listener) { | |
on(Socket.EVENT_CONNECT, listener) | |
mSocket?.connect() | |
} | |
fun logIn(@Nullable obj: Any, @Nullable ack: Ack) { | |
emit(SocketConstant.EMIT_LOGIN, obj, ack) | |
} | |
fun isConnected(): Boolean { | |
return mSocket?.connected()?:false | |
} | |
fun clearSession() { | |
mSocket?.off(SocketConstant.EMIT_LOGIN) | |
mSocket?.off(SocketConstant.EMIT_ORDER) | |
mSocket?.off(Socket.EVENT_CONNECT) | |
mSocket?.disconnect() | |
} | |
fun socket(): Socket? { | |
return mSocket | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment