创建 http4s websocket

问题描述 投票:0回答:0

我是一名新的 Scala 开发人员,目前,我需要 http4s 的一些支持。

一般来说,我有以下 Scala 代码

import pureconfig._
import pureconfig.generic.auto._

import scala.io.Source
import cats.effect.{ExitCode, IO, IOApp}
import fs2.Stream


object Runner extends IOApp {
  override def run(args: List[String]): IO[ExitCode] = {
    //get divisor
    val config = ConfigSource.file("config.yaml").loadOrThrow[AppConfig]
    println(s"Divisor: ${config.divisor}")

    //read csv file
    val fileName = "file.csv"
    val file = Source.fromFile(fileName)
    val lines = file.getLines().toSeq // here should be used toStream(), but toStream deprecated

    //split lines to stream
    val streams: Map[Int, Seq[String]] = lines.groupBy(line => line.toInt % config.divisor)
    // as a result -> HashMap(0 -> List(5, 10), 1 -> List(1, 6), 2 -> List(2, 7), 3 -> List(3, 8), 4 -> List(4, 9))

    println(streams)

    //Create streamValues
    val streamsValues: Map[Int, Int] = streams.map { case (k, v) =>
      k -> v.foldLeft(0) { (acc, s) => acc + s.toInt }
    }
    println(streamsValues)

    println(s"toSeq = ${streamsValues.toSeq}")

    val stream = Stream.emits(streamsValues.toList)
      .map { case (key, value) =>
        s"Key: $key, Value: $value"
      }
      .evalMap { str =>
        IO.delay(println(str))
      }

    stream.compile.drain.as(ExitCode.Success)
    
  }
}


case class AppConfig(divisor: Int)

有人可以帮我用 http4s 创建网络套接字吗

我的程序目前返回以下结果。

App result

有人可以帮我写一个带有 http4s 的网络套接字,它将返回下一个值(来自屏幕截图)

ws -> ws://localhost/ws?number=0 ,结果:15

ws -> ws://localhost/ws?number=1 ,结果:7

ws -> ws://localhost/ws?number=key ,结果:值(流中的键和值,请参阅提供的代码)

并解释它是如何工作的。关于如何创建网络套接字并在本地计算机上运行它的任何想法都会有所帮助

scala scala-cats cats-effect http4s fs2
© www.soinside.com 2019 - 2024. All rights reserved.