我正在編寫一個小測試程序來嘗試一些我需要在Scala項目中使用的Remote Actors。使Scala遠程演員更加穩定
基本目標是編寫一個服務器的測試應用程序,它可以處理一堆客戶端和更重要的客戶端,這些客戶端可以同時發送多個消息(如ping,更新請求和用戶引發的數據請求)
我想到的是這樣的: 簡要概述:客戶端啓動3個不同的角色,這些角色在不同偏移量的循環中再次啓動角色,以模擬相當隨機的消息。
import scala.actors.remote.RemoteActor
import scala.actors.remote.Node
import scala.actors.Actor
trait Request
trait Response
case object WhoAmI extends Request
case class YouAre(s:String) extends Response
case object Ping extends Request
case object Pong extends Response
case class PrintThis(s:String) extends Request
case object PrintingDone extends Response
object Server {
def main(args: Array[String]) {
val server = new Server
server.start
}
}
class Server extends Actor {
RemoteActor.alive(12345)
RemoteActor.register('server, this)
var count:Int = 0
def act() {
while(true) {
receive {
case WhoAmI => {
count += 1
sender ! YouAre(count.toString)
}
case Ping => sender ! Pong
case PrintThis(s) => {
println(s)
sender ! PrintingDone
}
case x => println("Got a bad request: " + x)
}
}
}
}
object Act3 extends scala.actors.Actor {
def act = {
var i = 0
Thread.sleep(900)
while (i <= 12) {
i += 1
val a = new Printer
a.start
Thread.sleep(900)
}
}
}
class Printer extends scala.actors.Actor {
def act = {
val server = RemoteActor.select(Node("localhost",12345), 'server)
server ! PrintThis("gagagagagagagagagagagagaga")
receive {
case PrintingDone => println("yeah I printed")
case _ => println("got something bad from printing")
}
}
}
object Act2 extends scala.actors.Actor {
def act = {
var i = 0
while (i < 10) {
i+=1
val a = new Pinger
a.start
Thread.sleep(700)
}
}
}
class Pinger extends scala.actors.Actor {
def act = {
val server = RemoteActor.select(Node("localhost",12345), 'server)
server ! Ping
receive {
case Pong => println("so I pinged and it fits")
case x => println("something wrong with ping. Got " + x)
}
}
}
object Act extends scala.actors.Actor {
def act = {
var i = 0
while(i < 10) {
i+=1
val a = new SayHi
a.start()
Thread.sleep(200)
}
}
}
class SayHi extends scala.actors.Actor {
def act = {
val server = RemoteActor.select(Node("localhost",12345), 'server)
server ! "Hey!"
}
}
object Client {
def main(args: Array[String]) {
Act.start()
//Act2.start()
Act3.start()
}
}
的問題是,事情不跑那樣順利,因爲我想指望他們: 當我開始只在客戶端的演員之一(通過註釋了其他人,因爲我在Client
與Act2
一樣)事情通常但並不總是順利。如果我啓動兩個或兩個以上的演員,則打印輸出通常會大量顯示(意味着:一次沒有任何事情發生,然後打印輸出顯得相當快)。此外,客戶端有時會終止,有時不會。
這可能不是最大的問題,但它們足以讓我覺得很不舒服。我在演員和遙遠的演員做了很多讀書,但我發現可用的信息相當缺乏。
試圖添加exit
聲明,如果它似乎適合。但是這並沒有幫助。
有人知道我做錯了什麼嗎?任何一般的詭計在這裏?一些dos和donts?
相關HTTP:// WWW。 artima.com/shop/actors_in_scala(但可能無法解決您的問題) – oluies 2010-11-03 13:20:18