jsMain.com.ditchoom.socket.NodeSocketExtensions.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of socket-js Show documentation
Show all versions of socket-js Show documentation
Simple multiplatform kotlin coroutines based socket.
package com.ditchoom.socket
import org.khronos.webgl.Uint8Array
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
suspend fun connect(tcpOptions: tcpOptions): Socket {
var netSocket: Socket? = null
suspendCoroutine {
val socket = Net.connect(tcpOptions) {
it.resume(Unit)
}
socket.on("error") { e ->
it.resumeWithException(RuntimeException(e.toString()))
}
netSocket = socket
}
return netSocket!!
}
suspend fun connect(tcpOptions: TcpSocketConnectOpts): Socket {
var netSocket: Socket? = null
suspendCoroutine {
val socket = Net.connect(tcpOptions) {
it.resume(Unit)
}
socket.on("error") { e ->
it.resumeWithException(RuntimeException(e.toString()))
}
netSocket = socket
}
return netSocket!!
}
suspend fun Socket.write(buffer: Uint8Array) {
suspendCoroutine {
write(buffer) {
it.resume(Unit)
}
}
}
suspend fun Socket.close() {
suspendCoroutine {
end {
it.resume(Unit)
}
}
}