blob: 94a53c9317635148ce76b8fe1449265329566e60 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
import kotlinx.coroutines.*
import java.net.ServerSocket
import java.net.Socket
import kotlin.coroutines.EmptyCoroutineContext
class MailServer(
val localhostName: String,
val scope: CoroutineScope = CoroutineScope(EmptyCoroutineContext)
) {
fun createAndLaunchHandlerFor(socket: Socket): Job {
val protocol = SMTPReceiveProtocol(localhostName, socket.inetAddress)
return protocol.executeAsync(scope + CoroutineName("connection handler from ${socket.inetAddress}"), Protocol.IO.FromSocket(socket))
}
suspend fun createServer(port: Int) {
listenToServerSocket(ServerSocket(port))
}
suspend fun listenToServerSocket(serverSocket: ServerSocket) {
withContext(Dispatchers.Unconfined) {
while (true) {
val newIncomingConnection =
withContext(Dispatchers.IO) { serverSocket.accept() }
createAndLaunchHandlerFor(newIncomingConnection)
}
}
}
}
|