1首先是sbt需要导入的依赖
name := "HttpServer" version := "1.0" scalaVersion := "2.11.8" libraryDependencies ++= Seq( "com.typesafe.akka" %% "akka-actor" % "2.4.8" , "com.typesafe.akka" %% "akka-agent" % "2.4.8", "com.typesafe.akka" %% "akka-slf4j" % "2.4.8", "com.typesafe.akka" %% "akka-testkit" % "2.4.8", "com.typesafe.akka" %% "akka-stream" % "2.4.8", "com.typesafe.akka" %% "akka-stream-testkit" % "2.4.8", "javax.servlet" % "javax.servlet-api" % "4.0.0-b06" )
2 scala代码
import java.net.{InetSocketAddress} import java.nio.ByteBuffer import java.nio.channels.{ServerSocketChannel, SocketChannel} import akka.actor.{Actor, ActorSystem, Props} /** * Created by derek on 17-5-29. */ object NioAkkaHttpServer extends App{ val system=ActorSystem("sys") val serverSocketChannel: ServerSocketChannel =ServerSocketChannel.open() serverSocketChannel.socket().setReuseAddress(true) serverSocketChannel.socket().bind(new InetSocketAddress(8080)) val nioActor=system.actorOf(Props[NioHandler],"handler") while(true) { nioActor ! serverSocketChannel.accept() } } class NioHandler extends Actor{ override def receive = { case socketchannel: SocketChannel=> val buffer = ByteBuffer.allocate(1024) socketchannel.read(buffer) buffer.flip() val request = decode(buffer) val temp = new StringBuffer temp.append("HTTP/1.1 200 OK\r\n") temp.append("Content-Type:text/html\r\n\r\n") println(request) val content=scala.io.Source.fromFile("/home/derek/Documents/test1.html").getLines().mkString temp.append("\r\n") temp.append(content) val bytes = temp.toString.getBytes("UTF-8"); socketchannel.write(ByteBuffer.wrap(bytes)) socketchannel.shutdownOutput() socketchannel.close() case _=> } def decode(buffer:ByteBuffer)={ new String(buffer.array()) } }
3 html提交请求到服务器
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<form method="post" action="http://localhost:8080">
name:<input type="text" name="name" /><br>
age:<input type="text" name="age" /><br>
<input type="submit" />
</form>
</body>
</html>
4上面test1.html
<html>
<body>
<h1>My First Heading</h1>
<a href="http://www.w3school.com.cn">W3School</a>
<p>My first paragraph.</p>
</body>
</html>
5用webbench测试并发
webbench -c 300 -t 60 http://localhost:8080/
Webbench - Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
Benchmarking: GET http://localhost:8080/
300 clients, running 60 sec.
Speed=1848419 pages/min, 1386312 bytes/sec.
Requests: 1848419 susceed, 0 failed.