summaryrefslogtreecommitdiff
path: root/src/main/kotlin/NetworkPacketTransporterJavaNet.kt
blob: 6badc3dbbfbda2adbe084213846cb1382999c4a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.io.InputStream
import java.io.OutputStream
import java.net.Socket

/*
TODO:
    - add TLS support
*/

/**
 * An implementation of [NetworkPacketTransporter] written using the [java.net] package.
 */
class NetworkPacketTransporterJavaNet : NetworkPacketTransporter {
    /**
     * The connection's socket.
     */
    private val socket: Socket = Socket(address, port.toInt())

    /**
     * The connection's input stream.
     */
    private val inStream: InputStream = this.socket.inputStream

    /**
     * The connection's output stream.
     */
    private val outStream: OutputStream = this.socket.outputStream

    constructor(address: String, port: UShort) : super(address, port)
    constructor(fullAddress: String) : super(fullAddress)

    override fun close() {
        if (this.socket.isClosed) {
            return
        }
        this.socket.close()
    }

    override fun transmit(payload: List<Byte>) {
        this.outStream.write(payload.toByteArray())
    }

    override fun receiveUntil(untilByte: Byte): List<Byte> {
        var stop = false
        val payload: MutableList<Byte> = MutableList(0, { 0 })
        while (!stop) {
            val b = this.inStream.readNBytes(1)[0]
            if (b == untilByte) {
                stop = true
                continue
            } else {
                payload.add(b)
            }
        }
        return payload
    }

    override fun receiveFixed(length: ULong): List<Byte> {
        return this.inStream.readNBytes(length.toInt()).toList()
    }
}