Personal tools
You are here: Home ブログ iwanaga Categories scala
« December 2010 »
Su Mo Tu We Th Fr Sa
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31  
Recent comments
Re:javascriptのthisについて inoue 2009-11-13
Re:Rhino Code Reading #0x04 iwanaga 2008-11-26
Re:Rhino Code Reading #0x04 inoue 2008-11-26
 
Document Actions

scala

Up one level

Document Actions

Re: Adaで超いい加減HTTPサーバ

Adaで超いい加減HTTPサーバ

> Goのgoroutine、Adaのタスクと来たら次はScalaのアクターで書くとどうなるのか、是非見てみたいですね。

import java.io._
import java.net._
import scala.actors.Actor
import scala.actors.Actor._
import scala.io.Source

case class Request(socket:Socket)
abstract class Status(httpVersion:String,statusCode:Int, reasonPhrase:String) {
override def toString = "%s %d %s".format(httpVersion, statusCode, reasonPhrase)
}
case object OK extends Status("HTTP/1.1", 200, "OK")
case object NotFound extends Status("HTTP/1.1", 404, "not found")

object Service extends Actor {
def act:Unit = {
loop {
react {
case Request(socket) =>
actor {
try {
val reader = new BufferedReader(new InputStreamReader(socket.getInputStream))
val writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream))

val path = parseRequest(reader)
writeResponse(writer, path)

reader.close
writer.close
} finally {
socket.close
}
}
}
}
}

private def parseRequest(reader:BufferedReader):String = {
val Array(action, uri, version) = reader.readLine.split(" ")
val list = uri.split("\\?&").toList
val path = "." + list.first

if (path.last == '/') {
path + "index.html"
} else if (new File(path).isDirectory) {
path + "/index.html"
} else {
path
}
}

private def writeResponse(writer:PrintWriter, path:String):Unit = {
val CRLF = "\r\n"
val file = new File(path)

if (file.exists) {
writer.print(OK + CRLF + CRLF)
val in = new FileInputStream(file)
try {
for(line <- Source.fromInputStream(in).getLines) {
writer.print(line + CRLF)
}
} finally {
in.close
}
} else {
writer.print(NotFound + CRLF + CRLF)
}

writer.flush
}
}

object Server {
Service.start

def start(port:Int) = {
val serverSocket = new ServerSocket(port)

while(true) {
val clientSocket = serverSocket.accept
Service ! Request(clientSocket)
}
}
}

Server.start(args(0).toInt)

並列処理で変った言語って他に何があったっけ?織田信長

Category(s)
scala
The URL to Trackback this entry is:
http://dev.ariel-networks.com/Members/iwanaga/scala-httpserver/tbping

Copyright(C) 2001 - 2006 Ariel Networks, Inc. All rights reserved.