src/Pure/Tools/server.scala
changeset 67794 82c5ca89ac61
parent 67793 d0eeaeab48cc
child 67795 f8037c7e4659
equal deleted inserted replaced
67793:d0eeaeab48cc 67794:82c5ca89ac61
    13 
    13 
    14 
    14 
    15 object Server
    15 object Server
    16 {
    16 {
    17   /* protocol */
    17   /* protocol */
       
    18 
       
    19   def split_line(line: String): (String, String) =
       
    20   {
       
    21     val head = line.takeWhile(c => Symbol.is_ascii_letter(c) || Symbol.is_ascii_letdig(c))
       
    22     val rest = line.substring(head.length).dropWhile(Symbol.is_ascii_blank(_))
       
    23     (head, proper_string(rest) getOrElse "{}")
       
    24   }
    18 
    25 
    19   val commands: Map[String, PartialFunction[(Server, JSON.T), JSON.T]] =
    26   val commands: Map[String, PartialFunction[(Server, JSON.T), JSON.T]] =
    20     Map(
    27     Map(
    21       "echo" -> { case (_, t) => t },
    28       "echo" -> { case (_, t) => t },
    22       "help" -> { case (_, JSON.empty) => commands.keySet.toList.sorted },
    29       "help" -> { case (_, JSON.empty) => commands.keySet.toList.sorted },
   222         var finished = false
   229         var finished = false
   223         while (!finished) {
   230         while (!finished) {
   224           connection.read_line() match {
   231           connection.read_line() match {
   225             case None => finished = true
   232             case None => finished = true
   226             case Some(line) =>
   233             case Some(line) =>
   227               val cmd = line.takeWhile(c => Symbol.is_ascii_letter(c) || Symbol.is_ascii_letdig(c))
   234               val (cmd, input) = Server.split_line(line)
   228               val input = line.substring(cmd.length).dropWhile(Symbol.is_ascii_blank(_))
       
   229               Server.commands.get(cmd) match {
   235               Server.commands.get(cmd) match {
   230                 case None => connection.reply_error("Bad command " + quote(cmd))
   236                 case None => connection.reply_error("Bad command " + quote(cmd))
   231                 case Some(body) =>
   237                 case Some(body) =>
   232                   proper_string(input) getOrElse "{}" match {
   238                   input match {
   233                     case JSON.Format(arg) =>
   239                     case JSON.Format(arg) =>
   234                       if (body.isDefinedAt((server, arg))) {
   240                       if (body.isDefinedAt((server, arg))) {
   235                         try { connection.reply_ok(body(server, arg)) }
   241                         try { connection.reply_ok(body(server, arg)) }
   236                         catch { case ERROR(msg) => connection.reply_error(msg) }
   242                         catch { case ERROR(msg) => connection.reply_error(msg) }
   237                       }
   243                       }