2019-06-02 20:59:05 +02:00
package org.hso.texturesyncclient.controller.net
import com.google.gson.*
import java.io.*
2019-06-02 22:04:01 +02:00
import java.lang.RuntimeException
2019-06-02 20:59:05 +02:00
import java.net.*
2019-06-02 22:04:01 +02:00
2019-06-02 20:59:05 +02:00
@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 )
2019-06-02 22:04:01 +02:00
val pkg = Packet . read ( io . first )
when ( pkg ) {
2019-06-02 20:59:05 +02:00
is JsonPacket -> return
2019-06-02 22:04:01 +02:00
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 " )
2019-06-02 20:59:05 +02:00
}
}
@Throws ( IOException :: class )
override fun close ( ) {
if ( output != null ) {
output !! . close ( )
}
if ( input != null ) {
input !! . close ( )
}
if ( socket != null ) {
socket !! . close ( )
}
}
}