我使用akka.net.Udp
发送UDP数据包(下面的代码)。发送到我的本地计算机(127.0.0.1)工作正常,但只要我用另一个IP地址运行相同的代码,akka就会抱怨“无效的参数”(下面的输出)。
任何想法出了什么问题?
package debug
import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import java.net.InetSocketAddress
import akka.io.{IO, Udp}
import akka.util.ByteString
class SocketTest extends Actor with ActorLogging {
val dest = new InetSocketAddress("131.179.196.46", 6363) // Invalid argument
// val dest = new InetSocketAddress("127.0.0.1", 6363) // works fine
val udp = context.actorOf(Props(classOf[UDP4]), name="udp4")
// send
Thread.sleep(1000)
udp ! (dest, ByteString("hello world"))
Thread.sleep(99999)
def receive = {???}
}
class UDP4 extends Actor with ActorLogging {
val local = new InetSocketAddress("127.0.0.1", 2222)
import context.system
IO(Udp) ! Udp.Bind(self, local)
def receive: Receive = {
case Udp.Bound(local) => context.become(ready(sender))
}
def ready(connection:ActorRef): Receive = {
case (remote:InetSocketAddress, data:ByteString) => {
log.info(s"Send to ${remote}: ${data}")
connection ! Udp.Send(data, remote)
}
case Udp.Received(data, remote) => log.info(s"Receive from ${remote}: ${data}")
case Udp.Unbind => connection ! Udp.Unbind
case Udp.Unbound => context.stop(self)
}
}
使用除本地计算机之外的任何其他目的地输出:
[DEBUG] [06/20/2016 11:54:39.753] [main] [EventStream(akka://Main)] logger log1-Logging$DefaultLogger started
[DEBUG] [06/20/2016 11:54:39.754] [main] [EventStream(akka://Main)] Default Loggers started
[DEBUG] [06/20/2016 11:54:39.851] [Main-akka.actor.default-dispatcher-2] [akka://Main/system/IO-UDP-FF/selectors/$a/0] Successfully bound to [/127.0.0.1:2222]
[INFO] [06/20/2016 11:54:40.783] [Main-akka.actor.default-dispatcher-5] [akka://Main/user/app/udp4] Send to /131.179.196.46:6363: ByteString(104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100)
[DEBUG] [06/20/2016 11:54:40.789] [Main-akka.actor.default-dispatcher-5] [akka://Main/system/IO-UDP-FF/selectors/$a/0] Invalid argument
[DEBUG] [06/20/2016 11:54:40.791] [Main-akka.actor.default-dispatcher-3] [akka://Main/system/IO-UDP-FF/selectors/$a/0] Closing DatagramChannel after being stopped
输出127.0.0.1作为目的地:
[DEBUG] [06/20/2016 11:55:37.213] [main] [EventStream(akka://Main)] logger log1-Logging$DefaultLogger started
[DEBUG] [06/20/2016 11:55:37.214] [main] [EventStream(akka://Main)] Default Loggers started
[DEBUG] [06/20/2016 11:55:37.280] [Main-akka.actor.default-dispatcher-4] [akka://Main/system/IO-UDP-FF/selectors/$a/0] Successfully bound to [/127.0.0.1:2222]
[INFO] [06/20/2016 11:55:38.234] [Main-akka.actor.default-dispatcher-2] [akka://Main/user/app/udp4] Send to /127.0.0.1:6363: ByteString(104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100)
答案 0 :(得分:1)
问题出在以下几行:
val local = new InetSocketAddress("127.0.0.1", 2222)
不仅需要本地绑定:
val local = new InetSocketAddress("0.0.0.0", 2222)
更改此行后,代码就像希望的那样工作。