42 lines
964 B
Kotlin
42 lines
964 B
Kotlin
package util.network.simulator
|
|
|
|
import kotlin.random.Random
|
|
|
|
class Network(threadGrupName: String = "network") {
|
|
private val nodes = mutableMapOf<Address, Node>()
|
|
private val addresses = mutableListOf<Address>()
|
|
val threadGroup = ThreadGroup(threadGrupName)
|
|
private val random by lazy { Random(System.currentTimeMillis()) }
|
|
|
|
operator fun get(address: Address): Node? {
|
|
return nodes[address]
|
|
}
|
|
|
|
fun addNode(node: Node) {
|
|
nodes[node.address] = node
|
|
addresses.add(node.address)
|
|
}
|
|
|
|
fun getRandomAddress(): Address {
|
|
val index = random.nextInt(addresses.size)
|
|
|
|
return addresses[index]
|
|
}
|
|
|
|
fun getRandomNode(): Node {
|
|
return nodes[getRandomAddress()]!!
|
|
}
|
|
|
|
fun start() {
|
|
nodes.forEach { (_, node) ->
|
|
node.start()
|
|
}
|
|
}
|
|
|
|
fun forEach(action: (Node) -> Unit) {
|
|
nodes.forEach { (_, node) ->
|
|
action(node)
|
|
}
|
|
}
|
|
}
|