Skip to content

Commit

Permalink
open connection socket just once
Browse files Browse the repository at this point in the history
  • Loading branch information
DatL4g committed Jul 20, 2024
1 parent a2f3b00 commit 8181c6c
Showing 1 changed file with 16 additions and 19 deletions.
35 changes: 16 additions & 19 deletions src/commonMain/kotlin/dev/datlag/k2k/connect/ConnectionServer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -39,28 +39,25 @@ internal class ConnectionServer(
close()

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

connectedSocket = socket.bind(socketAddress) {
reuseAddress = true
}.accept().also {
it.use { boundSocket ->
suspendCatching {
val readChannel = boundSocket.openReadChannel()
val buffer = ByteArray(readChannel.availableForRead)
while (true) {
val bytesRead = readChannel.readAvailable(buffer)
if (bytesRead <= 0) {
break
}

listener(buffer)
connectedSocket = socket.bind(socketAddress) {
reuseAddress = true
}.accept().also {
it.use { boundSocket ->
suspendCatching {
val readChannel = boundSocket.openReadChannel()
val buffer = ByteArray(readChannel.availableForRead)
while (true) {
val bytesRead = readChannel.readAvailable(buffer)
if (bytesRead <= 0) {
break
}
}.onFailure {
boundSocket.close()

listener(buffer)
}
}.onFailure {
boundSocket.close()
}
}
}
Expand Down

0 comments on commit 8181c6c

Please sign in to comment.