65 lines
1.6 KiB
Kotlin
65 lines
1.6 KiB
Kotlin
package org.hso.texturesyncclient.controller.net
|
|
|
|
import com.google.gson.*
|
|
import java.io.*
|
|
import java.lang.Exception
|
|
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)
|
|
|
|
when (Packet.read(io.first)) {
|
|
is JsonPacket -> return
|
|
is ErrorPacket -> throw Exception("TODO")
|
|
is BinaryPacket -> throw Exception("TODO")
|
|
}
|
|
}
|
|
|
|
@Throws(IOException::class)
|
|
override fun close() {
|
|
if (output != null) {
|
|
output!!.close()
|
|
}
|
|
if (input != null) {
|
|
input!!.close()
|
|
}
|
|
if (socket != null) {
|
|
socket!!.close()
|
|
}
|
|
}
|
|
|
|
} |