Skip to content

Commit c43e967

Browse files
REFACTOR - jvm-sdk/ network client 비동기 논블로킹으로 리팩토링
1 parent a3daffd commit c43e967

File tree

5 files changed

+51
-45
lines changed

5 files changed

+51
-45
lines changed

dummy/src/test/kotlin/MainIntegrationTest.kt

Lines changed: 1 addition & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -48,38 +48,11 @@ class MainIntegrationTest {
4848
)
4949
val serverUrl = mockWebServer.url("/collect").toString()
5050

51-
val result = dataCollector.collect(serverUrl, dummyUser)
52-
53-
assertTrue(result.isSuccess, "서버로의 데이터 전송이 실패")
51+
dataCollector.collect(serverUrl, dummyUser)
5452

5553
val request = mockWebServer.takeRequest()
5654
assertEquals("/collect", request.path, "요청 경로가 올바르지 않습니다.")
5755
assertEquals("POST", request.method, "HTTP 메서드가 올바르지 않습니다.")
5856
assertTrue(request.body.readUtf8().contains("Test User"), "전송된 데이터가 올바르지 않습니다.")
5957
}
60-
61-
@Test
62-
fun `통합 테스트 - 서버 오류 시 실패 처리`() {
63-
val mockResponse = MockResponse()
64-
.setResponseCode(500)
65-
.setBody("{ \"error\": \"Internal Server Error\" }")
66-
mockWebServer.enqueue(mockResponse)
67-
68-
val dummyUser = User(
69-
name = "Test User",
70-
age = 25,
71-
level = 5,
72-
score = 1000,
73-
achievements = listOf("Achievement1", "Achievement2"),
74-
active = true
75-
)
76-
val serverUrl = mockWebServer.url("/collect").toString()
77-
val result = dataCollector.collect(serverUrl, dummyUser)
78-
79-
// 검증
80-
assertTrue(result.isFailure, "서버 오류가 제대로 처리되지 않았습니다.")
81-
val exception = result.exceptionOrNull()
82-
assertNotNull(exception)
83-
assertEquals("Error: 500 - Server Error", exception!!.message)
84-
}
8558
}

jvm-sdk/build.gradle.kts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,7 @@ dependencies {
1414
implementation("com.fasterxml.jackson.core:jackson-core:$jacksonVersion")
1515
implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:$jacksonVersion")
1616
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:$jacksonVersion")
17+
18+
// coroutine
19+
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
1720
}
Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,62 @@
11
package com.gamedatahub.network
22

3+
import kotlinx.coroutines.CoroutineScope
4+
import kotlinx.coroutines.Dispatchers
5+
import kotlinx.coroutines.launch
36
import okhttp3.MediaType.Companion.toMediaType
47
import okhttp3.OkHttpClient
58
import okhttp3.Request
6-
import okhttp3.RequestBody
7-
9+
import kotlinx.coroutines.suspendCancellableCoroutine
10+
import okhttp3.*
11+
import okhttp3.RequestBody.Companion.toRequestBody
12+
import java.io.IOException
13+
import kotlin.coroutines.resume
14+
import kotlin.coroutines.resumeWithException
815

916
class JvmNetworkClient(
1017
private val client: OkHttpClient = OkHttpClient()
1118
) : NetworkClient {
19+
private val scope = CoroutineScope(Dispatchers.IO)
20+
21+
override fun postDataAsync(url: String, data: String) {
22+
scope.launch {
23+
try {
24+
val response = client.makePostRequest(url, data)
25+
TODO("성공 핸들링")
26+
} catch (e: Exception) {
27+
TODO("실패 핸들링")
28+
}
29+
}
30+
}
31+
}
1232

13-
override fun postData(url: String, data: String): Result<String> {
14-
return try {
15-
val requestBody = RequestBody.create("application/json".toMediaType(), data) // JSON 데이터 요청
16-
val request = Request.Builder()
17-
.url(url)
18-
.post(requestBody)
19-
.build()
33+
private suspend fun OkHttpClient.makePostRequest(url: String, data: String): String {
34+
val requestBody = data.toRequestBody("application/json".toMediaType())
35+
val request = Request.Builder()
36+
.url(url)
37+
.post(requestBody)
38+
.build()
2039

21-
client.newCall(request).execute().use { response ->
40+
return suspendCancellableCoroutine { continuation ->
41+
val call = this.newCall(request)
42+
43+
call.enqueue(object : Callback {
44+
override fun onResponse(call: Call, response: Response) {
2245
if (response.isSuccessful) {
23-
Result.success(response.body?.string() ?: "Success")
46+
continuation.resume(response.body?.string() ?: "")
2447
} else {
25-
Result.failure(Exception("Error: ${response.code} - ${response.message}"))
48+
continuation.resumeWithException(Exception("Error: ${response.code} - ${response.message}"))
2649
}
50+
response.close()
51+
}
52+
53+
override fun onFailure(call: Call, e: IOException) {
54+
continuation.resumeWithException(e)
2755
}
28-
} catch (e: Exception) {
29-
Result.failure(e) // 예외 처리
56+
})
57+
58+
continuation.invokeOnCancellation {
59+
call.cancel()
3060
}
3161
}
3262
}

shared-sdk/src/main/kotlin/com/gamedatahub/datacollection/DataCollector.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ class DataCollector<T>(
1010
private val jsonSerializer: JsonSerializer<T>
1111
) {
1212

13-
fun collect(serverUrl: String, data: T): Result<String> {
13+
fun collect(serverUrl: String, data: T) {
1414
val jsonData = serializeToJson(data)
15-
return networkClient.postData(serverUrl, jsonData)
15+
networkClient.postDataAsync(serverUrl, jsonData)
1616
}
1717

1818
private fun serializeToJson(data: T): String {

shared-sdk/src/main/kotlin/com/gamedatahub/network/NetworkClient.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,5 @@ package com.gamedatahub.network
22

33
interface NetworkClient {
44

5-
fun postData(url: String, data: String): Result<String>
5+
fun postDataAsync(url: String, data: String)
66
}

0 commit comments

Comments
 (0)