通过Akka http进行MJPEG流式传输

时间:2019-04-03 18:25:17

标签: scala akka akka-stream akka-http mjpeg

我有 Screenshoter 方法的 Source [Array [Byte],Any] 。我将其封存为 complete 方法的源,但是它不起作用,浏览器无法刷新图像。

implicit val toResponseMarshaller: ToResponseMarshaller[Source[Array[Byte], Any]] =
Marshaller.opaque { items =>
  val data = items.map(item => ChunkStreamPart(item))

  val customContentType = ContentType(MediaType.customBinary("image",
                                                             "jpeg", 
                                                             NotCompressible,
                                                             params = Map("boundary" -> "--BoundaryString")))

  val responseHeaders = List(RawHeader("Content-Type", "multipart/x-mixed-replace; boundary=--BoundaryString"))

  HttpResponse(StatusCodes.OK, headers = responseHeaders, entity = HttpEntity.Chunked(customContentType, data))
}


private val routes: Route =
    get {
      path("getpreview") {
          complete(Screenshoter.getScreenshotStream)
      }
    }

尝试通过Jetty(sparkjava)编写一些互联网示例。可以。

val httpServer = Service.ignite()
                        .port(8081)

httpServer.get("getpreview", (request: Request, response: Response) => {
    response.raw().setContentType("multipart/x-mixed-replace; boundary=--BoundaryString")
    val outputStream = response.raw().getOutputStream

    while (true) {
      val screenshot = Screenshoter.takeScreenshot

      outputStream.write(("Content-type: image/jpeg\r\n" +  "boundary:--BoundaryString\r\n" + "Content-Length: " + screenshot.length + "\r\n\r\n").getBytes)
      outputStream.write(screenshot)
      outputStream.write("\r\n\r\n".getBytes)
      outputStream.flush

      TimeUnit.MILLISECONDS.sleep(500)
    }

    response
})

在浏览器中,这些方法的所有标头(akka http和jetty)都相同。如何通过Akka http制作mjpeg流?

0 个答案:

没有答案