Scala equivalent of python echo server/client example?

前端 未结 5 1060
一个人的身影
一个人的身影 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:09

    You would have to use Java Sockets. I found a nice example of a Scala Socket Server/Client at: http://www.scala-lang.org/node/55

    0 讨论(0)
  • 2020-12-05 01:17

    Josh Suereth recently posted an example of an NIO echo server using scalaz Iteratees. Requires the scalaz library

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-05 01:32

    I just wrote a blog post about using Akka IO and Iteratees to create a simple command based socket server.

    Maybe it could be of interest.

    http://leon.radley.se/2012/08/akka-command-based-socket-server/

    0 讨论(0)
  • 2020-12-05 01:36

    You can use netty java library. Here is an example usage in Scala:

    https://github.com/mcroydon/scala-echo-server

    Generally you need to use Java Socket API. In this example Java Socket API are used, but the whole server is wrapped in Actor in order to process clients in separate thread and not to block acceptor thread (the same thing you will normally do in Java, but you will use threads directly).

    0 讨论(0)
提交回复
热议问题