How to serve static HTML file in Scala?

2019-08-17 01:07发布

问题:

I have an EchoServer that I was provided to run and serve static local HTML files on my computer. It would then put out an error if the files were non-existent. I want to know how do I provide a local file path in this code?

I'm practically new to the language and do not really know how it works.

This is my main class in which I try to run the server.

def main(args: Array[String]) {
    val server = new ServerSocket(9999)
    while(true) {
      try {
        serve(server)
        //Maybe the filepath goes here?
      }catch {
        case e: Exception => ("File not found")
      }

    }
  }

While these two is what takes in the input

object EchoServer {
  def read_and_write(in: BufferedReader, out:BufferedWriter): Unit = {
    out.write(in.readLine())
    out.flush()
    in.close()
    out.close()
  }

  def serve(server: ServerSocket): Unit = {
      val s = server.accept()
      val in = new BufferedReader(new InputStreamReader(s.getInputStream))
      val out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream))

      read_and_write(in, out)

      s.close()
  }

So if I get it to run properly it would read any existing HTML file, and if not output an error if it does not exist on my local machine.

回答1:

Echo server is relatively simple because it operates on ECHO Protocol[1]. If you need to serve static files, unless you want to implement your own protocol over TCP/UDP I would recommend you use any of the available web frameworks in Scala to do that over HTTP(s).

There are lot of web frameworks in Scala and most of them should support serving a folder or a static file right out of the web server.

A simple example using Scalatra would be to put the files you want to serve in the webapp folder and be done with it. You can read more about it here. If you want to perform any kind of validation on the input request you can also write a small API that do those validations post which can serve the files over the wire.

[1] - https://tools.ietf.org/html/rfc862



标签: scala