开始使用scala并且非常喜欢这种语言,但我似乎很难理解演员的工作方式。我之前使用NIO做了很多远程的东西,但现在我想尝试scala的远程演员。
我正在尝试创建一个非常简单的服务器和客户端(请参阅下面的代码)。
代码:
package testactors
import scala.collection.mutable.ArrayBuffer
import scala.actors._
import scala.actors.Actor._
import scala.actors.remote._
import scala.actors.remote.RemoteActor._
class Server extends Actor {
start
@volatile private var toLive = true
def act() {
alive(9000)
register('server, self)
while (toLive) {
receiveWithin(100) {
case TIMEOUT =>
case e => println(e)
}
}
println("Server died")
}
def killActor() {
toLive = false
}
}
object Main {
def main(args: Array[String]): Unit = {
val remoteSrc = new Server
println("Connecting to remote actor")
var localSrc = select(Node("localhost", 9000), 'server)
localSrc ! "hello"
Thread.sleep(1000)
println("Killing remote actor")
remoteSrc.killActor
}
}
输出结果为:
Connecting to remote actor
hello
Killing remote actor
Server died
但它一直在继续......
更新
SORRY!重复,第3次搜索找到答案: Is it bad practice to send an actor a message from something which is not an actor?