Scala equivalent of python echo server/client example?

前端 未结 5 1073
一个人的身影
一个人的身影 2020-12-05 00:33

All the \"server\" example in scala use actors, reactors etc...

Can someone show me how to write a dead simple echo server and client, just like the following python

5条回答
  •  失恋的感觉
    2020-12-05 01:32

    You can do following within standard library:

    // Simple server
    import java.net._
    import java.io._
    import scala.io._
    
    val server = new ServerSocket(9999)
    while (true) {
        val s = server.accept()
        val in = new BufferedSource(s.getInputStream()).getLines()
        val out = new PrintStream(s.getOutputStream())
    
        out.println(in.next())
        out.flush()
        s.close()
    }
    

    // Simple client
    import java.net._
    import java.io._
    import scala.io._
    
    val s = new Socket(InetAddress.getByName("localhost"), 9999)
    lazy val in = new BufferedSource(s.getInputStream()).getLines()
    val out = new PrintStream(s.getOutputStream())
    
    out.println("Hello, world")
    out.flush()
    println("Received: " + in.next())
    
    s.close()
    

    If you don't mind using extra libraries, you might like Finagle.

提交回复
热议问题