Hi! I trying to work with UDP sockets and have some problem. Every time I start my code, I have 50/5...
a

Andrey Gromov

over 6 years ago
Hi! I trying to work with UDP sockets and have some problem. Every time I start my code, I have 50/50 chance to start normally or receive java.net.SocketException: Already bound
private suspend fun eventLoop(port: Int) {
        val server = aSocket(ActorSelectorManager(<http://Dispatchers.IO|Dispatchers.IO>))
            .udp()
            .bind(InetSocketAddress(port))       <<<<<<<<<<< Exception
I'm sure that port is free on bind moment Stacktrace
Exception in thread "main" java.net.SocketException: Already bound
	at java.base/sun.nio.ch.Net.translateToSocketException(Net.java:164)
	at java.base/sun.nio.ch.DatagramSocketAdaptor.bind(DatagramSocketAdaptor.java:105)
	at io.ktor.network.sockets.UDPSocketBuilder.bind(Builders.kt:152)
	at io.ktor.network.sockets.UDPSocketBuilder.bind$default(Builders.kt:143)
	at co.fun.multiplayer.udp.ServerListener.eventLoop(ServerListener.kt:34)
	at co.fun.multiplayer.udp.ServerListener$start$1.invokeSuspend(ServerListener.kt:26)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:238)
	at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.kt:116)
	at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:80)
	at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:54)
	at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
	at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:36)
	at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
	at co.fun.multiplayer.udp.ServerListener.start(ServerListener.kt:25)
	at co.fun.multiplayer.udp.MainKt.main(Main.kt:14)
Caused by: java.nio.channels.AlreadyBoundException
	at java.base/sun.nio.ch.DatagramChannelImpl.bind(DatagramChannelImpl.java:784)
	at java.base/sun.nio.ch.DatagramSocketAdaptor.bind(DatagramSocketAdaptor.java:103)
	... 14 more
This workaround helping, but it is very ugly
var server: BoundDatagramSocket
        while (true) {
            try {
                server = aSocket(ActorSelectorManager(<http://Dispatchers.IO|Dispatchers.IO>))
                    .udp()
                    .bind(InetSocketAddress(port))
                break
            } catch (e: Exception) {

            }
        }