Scala ObjectInputStream 使程序失败无声



我有一个程序可以创建一个actor,然后从默认输入中读取。如果我写在使基本演员成为基本演员的特征上,它适用于"行动"方法:

 trait SocketActor extends Actor{

protected def sock:Socket

protected val in:BufferedReader=new BufferedReader(new InputStreamReader(this.sock.getInputStream()))
protected val out:PrintWriter= new PrintWriter(this.sock.getOutputStream(), true)
def act(){
     println("This get to be executed")
 }

如果我写以下内容,它不会执行 act 方法

 trait SocketActor extends Actor{

protected def sock:Socket

protected val in:ObjectInputStream=new ObjectInputStream(this.sock.getInputStream())
protected val out:ObjectOutputStream = new ObjectOutputStream (this.sock.getOutputStream())
def act(){
     println("This  doesn't get to be executed")
 }

Actor的创建可以按如下方式恢复:

import java.net._
import java.io._
import scala.io._
import game.io._
class PlayerActor(protected val sock:Socket) extends {
} with SocketActor
object TabuClient{
    def main(args:Array[String]){
    try{
        println("Always exected on both cases")
        val port=1337
        val s = new Socket(InetAddress.getByName("localhost"), port)
        val a=new PlayerActor(s)
        a.start()
        for (line <- io.Source.stdin.getLines){
            a.sendMessage(line)
        }
        s.close()
    }
    catch{
        case e:Throwable=>{
            e.printStackTrace()
        }
    }
}   

两种方式都编译,但第二种在 actor 启动后基本上失败而不抛出异常

对对象输入流执行以下操作解决了它,有趣的是,如果它只是一个输入流,它不需要懒惰

trait SocketActor extends Actor{

protected def sock:Socket

protected lazy val in:ObjectInputStream=new ObjectInputStream(this.sock.getInputStream())
protected lazy val out:ObjectOutputStream = new ObjectOutputStream (this.sock.getOutputStream())
def act(){
     println("This  doesn't get to be executed")
 }

最新更新