summaryrefslogtreecommitdiff
path: root/src/main/kotlin/NetworkPacketTransporter.kt
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/kotlin/NetworkPacketTransporter.kt')
-rw-r--r--src/main/kotlin/NetworkPacketTransporter.kt71
1 files changed, 71 insertions, 0 deletions
diff --git a/src/main/kotlin/NetworkPacketTransporter.kt b/src/main/kotlin/NetworkPacketTransporter.kt
new file mode 100644
index 0000000..86f651a
--- /dev/null
+++ b/src/main/kotlin/NetworkPacketTransporter.kt
@@ -0,0 +1,71 @@
+import java.io.Closeable
+
+/**
+ * [NetworkPacketTransporter] is an abstract class for network transport-layer operations. A class that implements this
+ * class' abstract methods, once instantiated, establishes and manages a connection with a remote endpoint defined by an
+ * address and a port and allows to send and receive network messages (also called "payloads").
+ *
+ * The address of the remote endpoint can be an IP address (v4 or v6) or a domain name, in which case it is resolved to
+ * an IP address right before initializing the connection. Every constructor should throw an [UnresolvableHostException]
+ * if the remote address is a domain name, but it cannot be resolved.
+ */
+abstract class NetworkPacketTransporter : Closeable {
+ val address: String
+ val port: UShort
+
+ /**
+ * Classic constructor.
+ *
+ * @throws UnresolvableHostException if the remote address is a domain name, but it cannot be resolved.
+ */
+ constructor(address: String, port: UShort) {
+ this.address = address
+ this.port = port
+ }
+
+ /**
+ * This constructor allows addresses specified using one of the styles specified in dial(2). See
+ * [nineAddressToValues].
+ *
+ * @throws UnresolvableHostException if the remote address is a domain name, but it cannot be resolved.
+ */
+ constructor(fullAddress: String) {
+ val ap = nineAddressToValues(fullAddress)
+ this.address = ap.first
+ this.port = ap.second
+ }
+
+ /**
+ * Close the connection.
+ */
+ abstract override fun close()
+
+ /**
+ * Transmit a payload.
+ *
+ * @throws java.io.IOException if the message could not be correctly transmitted.
+ */
+ abstract fun transmit(payload: List<Byte>)
+
+ /**
+ * Receive a payload until a byte occurs, which marks the end of the message. The byte is discarded after being read
+ * and is not returned.
+ *
+ * If you know both which byte marks the end of the message and the message length, it is advised to use
+ * [receiveFixed] instead, which is usually more efficient.
+ *
+ * @param untilByte The byte that marks the end of the message.
+ *
+ * @throws java.io.IOException if the message could not be correctly received.
+ */
+ abstract fun receiveUntil(untilByte: Byte): List<Byte>
+
+ /**
+ * Receive a payload with fixed length.
+ *
+ * @param length The length of the message in bytes.
+ *
+ * @throws java.io.IOException if the message could not be correctly received.
+ */
+ abstract fun receiveFixed(length: ULong): List<Byte>
+} \ No newline at end of file