Klient2Klient

Kotlin Multiplatform

This is a Kotlin Multiplatform project, however it is implemented and works ONLY on JVM right now. This means any JVM project/platform can use this library, so Android and Java Desktop/Server applications can run it.

Issues Stars Forks Contributors License

Kotlin IntelliJ IDEA

Discover and create Peer to Peer connections easily

  • Discover hosts in the same network
  • Connect and transfer data among clients

Table of contents

Discovery

The discovery relies on a builder

  • setDiscoveryTimeout(milliSecondsOrDuration) after which time it stops discovering (searching for other hosts)
  • setDiscoveryTimeoutListener{ } called in IO dispatcher but is a suspend function, so you can switch context easily
  • setDiscoverableTimeout(milliSecondsOrDuration) after which time it stops broadcasting to other hosts (cannot be discovered anymore)
  • setDiscoverableTimeoutListener{ } called in IO dispatcher but is a suspend function, so you can switch context easily
  • setPing(milliSecondsOrDuration) at which interval it broadcasts to other hosts
  • setPuffer(milliSecondsOrDuration) tolerance in which time the hosts need to ping again (since it’s UDP, packages may be lost or not sent)
  • setPort(int) on which port to broadcast and listen
  • setHostFilter(regex) the discovered hosts need to match this (keep empty (and filterMatch in Host) for any or change the regex to “.*”)
  • setScope(coroutineScope) change the scope in which the discovery jobs are running in
  • setHostIsClient(boolean) whether the current host should be discovered ass a client too (default off)
  • build() create an instance of Discovery

The builder can be called using two different methods.

val discover = Discovery.Builder(coroutneScope /* optional */)
  .setPort(1337)
  .otherBuilderMethods()
  .build()

val discover = coroutineScope.discovery {
  setPort(1337)
  otherBuilderMethods()
}

Make discoverable (can be found by other hosts)

Basically the host holds three parameter

  • name: the name of the host
  • filterMatch: the String to match the hostFilter regex
  • optionalInfo: any JsonElement

Call any of the following methods:

discover.makeDiscoverable(Host("name", "filterMatch" /* optional */, jsonElement /* optional */))
discover.makeDiscoverable("name", "filterMatch" /* optional */, jsonElement /* optional */)
discover.makeDiscoverable("name", "filterMatch" /* optional */, "{jsonString: true}" /* optional */)

To stop being discoverable imply call

discover.stopBeingDiscoverable()

Start discovery (find other hosts)

discover.startDiscovery()
//or
discover.startDiscovery(hostIsClient)

To stop discovery simply call

discover.stopDiscovery()

Get the found hosts

To get the current list of found hosts synchronously use:

val setOfHosts = discover.peers

The host list can be collected to always get the latest items

discover.peersFlow.collect { hosts ->
  // got new hosts
}

GitHub

View Github