Skip to content

Commit 6870b44

Browse files
committed
Allow multiple clients to connect at once
1 parent 8e5ef8f commit 6870b44

File tree

1 file changed

+28
-25
lines changed

1 file changed

+28
-25
lines changed

mod/src/main/kotlin/gay/object/mlogv32/ProcessorAccess.kt

Lines changed: 28 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,13 @@ class ProcessorAccess(
109109
try {
110110
val selector = SelectorManager(Dispatchers.IO)
111111
aSocket(selector).tcp().bind(hostname, port).use { serverSocket ->
112-
runServer(serverSocket)
112+
while (true) {
113+
Log.info("Waiting for clients...")
114+
val client = serverSocket.accept()
115+
launch {
116+
handleClient(client)
117+
}
118+
}
113119
}
114120
} catch (e: Exception) {
115121
Log.err("ProcessorAccess server failed", e)
@@ -200,32 +206,29 @@ class ProcessorAccess(
200206
return proc to ramVariable.mod(RAM_PROC_VARS)
201207
}
202208

203-
private suspend fun runServer(serverSocket: ServerSocket) {
204-
while (true) {
205-
Log.info("Waiting for clients...")
206-
serverSocket.accept().use { client ->
207-
Log.info("Client connected!")
208-
val rx = client.openReadChannel()
209-
val tx = client.openWriteChannel(true)
210-
while (true) {
211-
val response: Response = try {
212-
val line = rx.readUTF8Line() ?: break
213-
Log.info("Got request: $line")
214-
val request = Json.decodeFromString<Request>(line)
215-
request.handle(this, rx, tx)
216-
} catch (e: CancellationException) {
217-
throw e
218-
} catch (e: IllegalArgumentException) {
219-
Log.err("Bad request", e)
220-
ErrorResponse.badRequest(e)
221-
} catch (e: Exception) {
222-
Log.err("Request failed", e)
223-
ErrorResponse(e)
224-
}
225-
tx.writeStringUtf8(Json.encodeToString(response) + "\n")
209+
private suspend fun handleClient(client: Socket) {
210+
client.use {
211+
Log.info("Client connected!")
212+
val rx = client.openReadChannel()
213+
val tx = client.openWriteChannel(true)
214+
while (true) {
215+
val response: Response = try {
216+
val line = rx.readUTF8Line() ?: break
217+
Log.info("Got request: $line")
218+
val request = Json.decodeFromString<Request>(line)
219+
request.handle(this@ProcessorAccess, rx, tx)
220+
} catch (e: CancellationException) {
221+
throw e
222+
} catch (e: IllegalArgumentException) {
223+
Log.err("Bad request", e)
224+
ErrorResponse.badRequest(e)
225+
} catch (e: Exception) {
226+
Log.err("Request failed", e)
227+
ErrorResponse(e)
226228
}
227-
Log.info("Client disconnected.")
229+
tx.writeStringUtf8(Json.encodeToString(response) + "\n")
228230
}
231+
Log.info("Client disconnected.")
229232
}
230233
}
231234

0 commit comments

Comments
 (0)