Skip to content

Commit

Permalink
passing more Java version's tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Piasy committed Jan 13, 2025
1 parent ecfd74c commit 951018f
Show file tree
Hide file tree
Showing 22 changed files with 952 additions and 842 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ IO.socket("http://localhost:3000", IO.Options()) { socket ->
}
```

Most of the APIs are the same as socket.io-client-java, here are some differences:

- Create socket is asyncronous, to make it's easier to guarantee thread safety.
- Binary messages can't be nested, because `emit` only accepts String/Boolean/Number/JsonElement/ByteArray, other types will be converted to String using `toString()`, so there is no way to put ByteArray in JsonElement.

## Example

### Android
Expand Down
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ plugins {
alias(libs.plugins.versionUpdate)
}

// ./gradlew versionCatalogUpdate
versionCatalogUpdate {
sortByKey = false
keep {
Expand Down
11 changes: 5 additions & 6 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,21 @@ iosDeploymentTarget = "14.0"
compileSdk = "35"
minSdk = "21"
targetSdk = "35"
agp = "8.7.2"
agp = "8.8.0"
kotlin = "2.1.0"
mockk = "1.13.13"
mockk = "1.13.16"
ktor = "3.0.3"
coroutine = "1.10.1"
compose = "1.7.5"

[libraries]
junit = "junit:junit:4.13.2"
hamcrest = "org.hamcrest:hamcrest-library:1.3"
hamcrest = "org.hamcrest:hamcrest-library:3.0"
kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
mockk = { module = "io.mockk:mockk", version.ref = "mockk" }
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutine" }
json = "org.json:json:20241224"

socketioParser = "org.hildan.socketio:socketio-kotlin:1.6.0"
json = "org.json:json:20250107"
socketioParser = "org.hildan.socketio:socketio-kotlin:1.7.1"
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutine" }
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-websockets = { module = "io.ktor:ktor-client-websockets", version.ref = "ktor" }
Expand Down
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#Wed Nov 16 22:27:43 CST 2022
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class EngineSocket(

internal var disablePingTimeout = false // to help unit test
private var state = State.INIT
private var id = ""
internal var id = ""
private var upgrades = emptyList<String>()
private var pingInterval = 0
private var pingTimeout = 0
Expand Down Expand Up @@ -317,7 +317,6 @@ class EngineSocket(
val data = packet.payload
if (data != null) {
emit(EVENT_DATA, data)
emit(EVENT_MESSAGE, data)
}
}

Expand Down Expand Up @@ -591,7 +590,7 @@ class EngineSocket(
/**
* Called when data is received from the server.
*/
const val EVENT_MESSAGE = "message"
const val EVENT_DATA = "data"

/**
* Called when an error occurs.
Expand All @@ -618,7 +617,6 @@ class EngineSocket(
const val EVENT_PACKET = "packet"
const val EVENT_PACKET_CREATE = "packetCreate"
const val EVENT_HEARTBEAT = "heartbeat"
const val EVENT_DATA = "data"
const val EVENT_PING = "ping"

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import io.ktor.util.date.*
import kotlinx.coroutines.CoroutineScope
import org.hildan.socketio.EngineIO
import org.hildan.socketio.EngineIOPacket
import org.hildan.socketio.InvalidSocketIOPacketException
import kotlin.jvm.JvmField

abstract class Transport(
Expand Down Expand Up @@ -89,18 +90,26 @@ abstract class Transport(
}

@WorkThread
protected fun onWsData(data: String) {
logD("onData: `$data`")
if (stringMessagePayloadForTesting) {
onPacket(EngineIO.decodeWsFrame(data, deserializePayload = { it }))
} else {
onPacket(EngineIO.decodeSocketIO(data))
protected fun onWsText(data: String) {
logD("onWsText: `$data`")
val packet = try {
if (stringMessagePayloadForTesting) {
EngineIO.decodeWsFrame(data, deserializePayload = { it })
} else {
EngineIO.decodeSocketIO(data)
}
} catch (e: InvalidSocketIOPacketException) {
val log = "onWsText decode error: ${e.message}"
logE(log)
onError(log)
return
}
onPacket(packet)
}

@WorkThread
protected fun onWsData(data: ByteArray) {
// TODO: binary
protected fun onWsBinary(data: ByteArray) {
}

@WorkThread
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ import io.ktor.util.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.hildan.socketio.EngineIO
import org.hildan.socketio.EngineIOPacket
import org.hildan.socketio.SocketIO
import org.hildan.socketio.SocketIOPacket
import org.hildan.socketio.*

open class PollingXHR(
opt: Options,
Expand Down Expand Up @@ -138,10 +135,17 @@ open class PollingXHR(
@WorkThread
private fun onPollComplete(data: String) {
logD("onPollComplete: state $state, `$data`")
val packets = if (stringMessagePayloadForTesting) {
EngineIO.decodeHttpBatch(data, deserializeTextPayload = { it })
} else {
EngineIO.decodeHttpBatch(data, SocketIO::decode)
val packets = try {
if (stringMessagePayloadForTesting) {
EngineIO.decodeHttpBatch(data, deserializeTextPayload = { it })
} else {
EngineIO.decodeHttpBatch(data, SocketIO::decode)
}
} catch (e: InvalidSocketIOPacketException) {
val log = "onPollComplete decode error: ${e.message}"
logE(log)
onError(log)
return
}
for (pkt in packets) {
if ((state == State.OPENING || state == State.CLOSING) && pkt is EngineIOPacket.Open) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,11 @@ open class WebSocket(
logD("Receive frame: $frame")
when (frame) {
is Frame.Text -> {
scope.launch { onWsData(frame.readText()) }
scope.launch { onWsText(frame.readText()) }
}

is Frame.Binary -> {
scope.launch { onWsData(frame.readBytes()) }
scope.launch { onWsBinary(frame.readBytes()) }
}

is Frame.Close -> {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
package com.piasy.kmp.socketio.logging

import io.ktor.util.date.*

interface LoggerInterface {
fun debug(tag: String, log: String)
fun info(tag: String, log: String)
fun error(tag: String, log: String)
}

internal object Logger : LoggerInterface {
internal var logger: LoggerInterface = DefaultLogger
private var logger: LoggerInterface = DefaultLogger

fun setLogger(logger: LoggerInterface) {
this.logger = logger
}

override fun debug(tag: String, log: String) {
logger.debug(tag, log)
Expand All @@ -24,14 +30,14 @@ internal object Logger : LoggerInterface {

private object DefaultLogger : LoggerInterface {
override fun debug(tag: String, log: String) {
println("D $tag $log")
println("${GMTDate().timestamp} D $tag $log")
}

override fun info(tag: String, log: String) {
println("I $tag $log")
println("${GMTDate().timestamp} I $tag $log")
}

override fun error(tag: String, log: String) {
println("E $tag $log")
println("${GMTDate().timestamp} E $tag $log")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ class Manager(
}
field = value
}
@JvmField
var auth: Map<String, String> = emptyMap()

/**
Expand Down Expand Up @@ -168,8 +169,8 @@ class Manager(
val socket = engine ?: return
subs.add(On.on(socket, EngineSocket.EVENT_DATA, object : Listener {
override fun call(vararg args: Any) {
if (args.isNotEmpty() && args[0] is SocketIOPacket) {
Logger.debug(TAG, "on SocketIOPacket ${args[0]}")
if (args.isNotEmpty()) {
Logger.debug(TAG, "on EngineSocket data ${args[0]::class}")
emit(EVENT_PACKET, args[0])
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,8 @@ class Socket(
is SocketIOPacket.Disconnect -> onDisconnect()
is SocketIOPacket.ConnectError -> {
destroy()
super.emit(EVENT_CONNECT_ERROR, packet.errorData?.toString() ?: "Connect error")
val data = packet.errorData ?: JsonObject(emptyMap())
super.emit(EVENT_CONNECT_ERROR, data)
}

is SocketIOPacket.Event -> onEvent(packet)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public abstract class Connection {

@Before
public void startServer() throws IOException, InterruptedException {
TestUtil.setupLogger();
TestUtil.stringMessagePayloadForTesting(false);
logger.fine("Starting server ...");

final CountDownLatch latch = new CountDownLatch(1);
Expand Down

This file was deleted.

Loading

0 comments on commit 951018f

Please sign in to comment.