Created
August 15, 2021 21:51
-
-
Save eutkin/1a168c71aec9df9003615008b1d630ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.InetSocketAddress | |
import java.nio.ByteBuffer | |
import java.nio.ByteOrder | |
import java.nio.channels.FileChannel | |
import java.nio.channels.SocketChannel | |
import java.nio.file.Files | |
import java.nio.file.Path | |
import java.nio.file.StandardOpenOption.* | |
fun main(args: Array<String>) { | |
val (dir) = args | |
Files | |
.list(Path.of(dir)) | |
.use { paths -> | |
paths.forEach { path -> | |
SocketChannel.open(InetSocketAddress(8888)).use { socketChannel -> | |
FileChannel.open(path, READ) | |
.use { inputFileChannel -> | |
FileChannel.open( | |
Path.of(path.toFile().name.replaceFirst("in", "out")), | |
CREATE, | |
APPEND, | |
WRITE | |
) | |
.use { outputChannel -> | |
val start = System.currentTimeMillis() | |
var counter = 0 | |
val buffer = ByteBuffer.allocate(2) | |
while (true) { | |
val position = inputFileChannel.position() | |
val readBytes = inputFileChannel.read(buffer) | |
if (readBytes < buffer.capacity()) { | |
break | |
} | |
val size = buffer.flip().order(ByteOrder.BIG_ENDIAN).short.toLong() | |
buffer.clear() | |
val transferBytes = | |
inputFileChannel.transferTo(position, size + readBytes, socketChannel) | |
inputFileChannel.position(position + transferBytes) | |
if (transferBytes < size) { | |
break | |
} | |
val readResponseBytes = socketChannel.read(buffer) | |
if (readResponseBytes < buffer.capacity()) { | |
break | |
} | |
val outputPosition = outputChannel.position() | |
val responseSize = buffer.flip().order(ByteOrder.BIG_ENDIAN).short.toLong() | |
buffer.clear() | |
val transferResponseBytes = outputChannel.transferFrom( | |
socketChannel, | |
outputChannel.position(), | |
responseSize | |
) | |
outputChannel.position(outputPosition + transferResponseBytes) | |
counter++ | |
} | |
println("${System.currentTimeMillis() - start} ms for $counter transactions") | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment