提高 writeAndFlush 的性能

This commit is contained in:
tursom 2019-11-21 00:08:19 +08:00
parent 1e388ad670
commit cb61ac0ca7
5 changed files with 18 additions and 3 deletions

View File

@ -15,8 +15,8 @@ interface SocketWriter<T> : Closeable {
value.forEach { write(it) }
}
suspend fun writeAndFlush(value: T, timeout: Long) {
suspend fun writeAndFlush(value: T, timeout: Long = 0): Long {
write(value)
flush(timeout)
return flush(timeout)
}
}

View File

@ -12,6 +12,6 @@ class ByteArrayWriter(
}
override suspend fun flush(timeout: Long): Long = prevWriter.flush(timeout)
override suspend fun writeAndFlush(value: ByteArray, timeout: Long): Long = prevWriter.writeAndFlush(HeapByteBuffer(value), timeout)
override fun close() = prevWriter.close()
}

View File

@ -22,6 +22,14 @@ class SocketWriterImpl(
return read
}
override suspend fun writeAndFlush(value: ByteBuffer, timeout: Long): Long {
return if (bufList.isEmpty()) {
socket.write(value, timeout).toLong()
} else {
super.writeAndFlush(value, timeout)
}
}
override fun close() {
socket.close()
}

View File

@ -8,5 +8,6 @@ class StringObjectWriter(
) : SocketWriter<Any> {
override suspend fun write(value: Any) = prevWriter.write(toString(value))
override suspend fun flush(timeout: Long) = prevWriter.flush(timeout)
override suspend fun writeAndFlush(value: Any, timeout: Long): Long = prevWriter.writeAndFlush(toString(value), timeout)
override fun close() = prevWriter.close()
}

View File

@ -21,4 +21,10 @@ class StringWriter(
override fun close() {
prevWriter.close()
}
override suspend fun writeAndFlush(value: String, timeout: Long): Long = if (stringList.isEmpty()) {
prevWriter.writeAndFlush(HeapByteBuffer(value.toByteArray()), timeout)
} else {
super.writeAndFlush(value, timeout)
}
}