103 lines
2.7 KiB
Kotlin
103 lines
2.7 KiB
Kotlin
package org.hso.texturesyncclient.controller.net
|
|
|
|
import com.google.gson.*
|
|
import java.io.*
|
|
import java.lang.RuntimeException
|
|
import java.net.*
|
|
|
|
|
|
@Suppress("MemberVisibilityCanBePrivate")
|
|
class Connection(val addr: InetAddress, val port: Int = 10796) : Closeable {
|
|
|
|
var socket: Socket? = null
|
|
var output: DataOutputStream? = null
|
|
var input: DataInputStream? = null
|
|
|
|
@Throws(IOException::class)
|
|
private fun getStreams(): Pair<DataInputStream, DataOutputStream> {
|
|
val i: DataInputStream
|
|
val o: DataOutputStream
|
|
|
|
if (socket == null || !socket!!.isConnected) {
|
|
val sock = Socket(addr, port)
|
|
i = DataInputStream(BufferedInputStream(sock.getInputStream()))
|
|
o = DataOutputStream(BufferedOutputStream(sock.getOutputStream()))
|
|
|
|
input = i
|
|
output = o
|
|
socket = sock
|
|
} else {
|
|
i = input!!
|
|
o = output!!
|
|
}
|
|
|
|
return Pair(i, o)
|
|
}
|
|
|
|
@Throws(IOException::class)
|
|
fun ping() {
|
|
val io = getStreams()
|
|
|
|
val obj = JsonObject()
|
|
obj.add("ping", JsonObject())
|
|
|
|
JsonPacket(obj).write(io.second)
|
|
|
|
val pkg = Packet.read(io.first)
|
|
|
|
when (pkg) {
|
|
is JsonPacket -> return
|
|
is BinaryPacket -> throw ConnectionUnexpectedPacket()
|
|
is ErrorPacket -> throw ConnectionErrorException(pkg)
|
|
else -> throw RuntimeException("Unreachable")
|
|
}
|
|
}
|
|
|
|
fun query(query : Array<String>) : Array<InternalTexture> {
|
|
val io = getStreams()
|
|
|
|
val obj = JsonObject()
|
|
obj.add("query", {
|
|
val inner = JsonObject();
|
|
inner.add("query", {
|
|
val array = JsonArray()
|
|
for(queryString in query) {
|
|
array.add(queryString)
|
|
}
|
|
array
|
|
}())
|
|
inner
|
|
}())
|
|
|
|
JsonPacket(obj).write(io.second)
|
|
|
|
val pkg = Packet.read(io.first)
|
|
|
|
when (pkg) {
|
|
is JsonPacket -> {
|
|
try {
|
|
return Gson().fromJson<Array<InternalTexture>>(pkg.content, Array<InternalTexture>::class.java)
|
|
} catch (e : JsonSyntaxException ){
|
|
throw ConnectionInvalidJsonException(e)
|
|
}
|
|
}
|
|
is BinaryPacket -> throw ConnectionUnexpectedPacket()
|
|
is ErrorPacket -> throw ConnectionErrorException(pkg)
|
|
else -> throw RuntimeException("Unreachable")
|
|
}
|
|
}
|
|
|
|
@Throws(IOException::class)
|
|
override fun close() {
|
|
if (output != null) {
|
|
output!!.close()
|
|
}
|
|
if (input != null) {
|
|
input!!.close()
|
|
}
|
|
if (socket != null) {
|
|
socket!!.close()
|
|
}
|
|
}
|
|
|
|
} |