Skip to content

Commit

Permalink
Fix Socket Close
Browse files Browse the repository at this point in the history
  • Loading branch information
naotiki committed May 24, 2023
1 parent 7f8d7e5 commit 20c2648
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions client-app/src/main/kotlin/server/Server.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,23 @@ import kotlinx.serialization.decodeFromByteArray
import java.io.DataInputStream
import java.net.ServerSocket
import java.net.Socket
import java.net.SocketException
import java.nio.ByteBuffer
class Server(val port: Int=PORT) {
val serverSocket = ServerSocket(port)

suspend fun runServer()= withContext(Dispatchers.IO){
suspendCancellableCoroutine<Unit> {
it.invokeOnCancellation { serverSocket.close() }
while (it.isActive){
val socket=serverSocket.accept()
ServerThread(socket).start()
runCatching {
while (it.isActive){
val socket=serverSocket.accept()
ServerThread(socket).start()
}
}.onFailure { throwable ->
if (throwable is SocketException){
throwable.printStackTrace()
}else throw throwable
}
println("Server Shutdown")
}
Expand Down

0 comments on commit 20c2648

Please sign in to comment.