Skip to content

Commit

Permalink
close previous socket when receiving data and expose connection close…
Browse files Browse the repository at this point in the history
… methods
  • Loading branch information
DatL4g committed Jul 20, 2024
1 parent 5ddd905 commit 17d9961
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
24 changes: 21 additions & 3 deletions src/commonMain/kotlin/dev/datlag/k2k/connect/Connection.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package dev.datlag.k2k.connect
import kotlinx.coroutines.CoroutineScope
import dev.datlag.k2k.Dispatcher
import dev.datlag.k2k.Host
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.properties.Delegates

Expand All @@ -15,21 +16,38 @@ class Connection private constructor(
private val client = ConnectionClient(immediate)
private val server = ConnectionServer(immediate)

private var sendJob: Job? = null

suspend fun sendNow(byteArray: ByteArray, peer: Host) = client.send(byteArray, peer, port)

fun send(byteArray: ByteArray, peer: Host) = scope.launch(Dispatcher.IO) {
sendNow(byteArray, peer)
fun send(byteArray: ByteArray, peer: Host) {
sendJob?.cancel()

sendJob = scope.launch(Dispatcher.IO) {
sendNow(byteArray, peer)
}
}

fun receive(listener: suspend (ByteArray) -> Unit) {
server.receive(port, scope, listener)
}

override fun close() {
fun stopSending() {
sendJob?.cancel()
sendJob = null

client.close()
}

fun stopReceiving() {
server.close()
}

override fun close() {
stopSending()
stopReceiving()
}

class Builder(private var scope: CoroutineScope = CoroutineScope(Dispatcher.IO)) {
private var port by Delegates.notNull<Int>()
private var immediate: Boolean = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ internal class ConnectionServer(
scope: CoroutineScope,
listener: suspend (ByteArray) -> Unit
) {
receiveJob?.cancel()
close()

receiveJob = scope.launch(Dispatcher.IO) {
while (currentCoroutineContext().isActive) {
val socketAddress = InetSocketAddress(NetInterface.getLocalAddress(), port)
Expand Down

0 comments on commit 17d9961

Please sign in to comment.