Skip to content

Instantly share code, notes, and snippets.

@redacted-dev
Last active August 16, 2019 02:13
Show Gist options
  • Save redacted-dev/aa4c143b40845bfb31aa25876820c627 to your computer and use it in GitHub Desktop.
Save redacted-dev/aa4c143b40845bfb31aa25876820c627 to your computer and use it in GitHub Desktop.
Passing data across sockets with Kotlin (JVM)

[Redacted]

[Redacted]

  • main.kt
  • methods.kt
  • data.kt

Main is where I run the app. This is a threaded one. I wanted to know how to Implement in Kotling.

In Methods the appliction performs the connection and sends the data

Data serves just as a model. Is the kind of Object the app sends.

// As you can see, the class definition also contains the default constructor. Reminds me of TypeScript
class mainThread constructor(val greet: String) : Runnable{
//Step TWO
init {
Thread(this, "Server").start();
}
//Step THREE
override fun run() {
methods(greet).build()
}
}
//Step ONE
fun main(args: Array<String>) {
print("Write something: ")
mainThread(readLine()!!)
println("Your message will be sent to the first connection attempt...")
}
import java.io.ObjectOutputStream
import java.net.InetAddress
import java.net.ServerSocket
class methods(val greet: String) { //The constructor keyword is not needed for default constructors
//Apologies for the generic name of the fn though.
public fun build(){
println("Waiting for client...")
val server = ServerSocket(1337) //Look, there is no new keyword. Nonewhere
val conn = server.accept();
if (conn.isConnected){
val guest = conn.remoteSocketAddress
println("$guest connected!")
server.close()
val output = ObjectOutputStream(conn.getOutputStream())
val host = InetAddress.getLocalHost().hostName
val data = data(host, greet)
output.writeObject(data)
output.flush()
output.close()
println("Job finished. Sent $greet from $host")
}
}
}
import java.io.Serializable
//Please just don't mind this
class data(val user: String, val msg: String) : Serializable //No braces
import java.io.ObjectInputStream
import java.net.Socket
fun main(args: Array<String>) {
println("I am meant to receive something from someone...")
println("Tell me which machine shall I Connect:")
val server = readLine()!!
val conn = Socket(server, 1337)
if (conn.isConnected) handshake(conn)
}
fun handshake(conn: Socket){
val input = ObjectInputStream(conn.getInputStream())
val result:data = input.readObject() as data //Interesting Type casting here
println("Got it!")
println("${result.user} says ${result.msg}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment