2010/01/10
Re: 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