Scala equivalent of python echo server/client exam

2019-01-13 19:20发布

问题:

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 example of Server and Client:

# A simple echo server 
import socket 

host = '' 
port = 50000 
backlog = 5 
size = 1024 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind((host,port)) 
s.listen(backlog) 
while 1: 
    client, address = s.accept() 
    data = client.recv(size) 
    if data: 
        client.send(data) 
    client.close()

# A simple echo client 
import socket 

host = 'localhost' 
port = 50000 
size = 1024 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect((host,port)) 
s.send('Hello, world') 
data = s.recv(size) 
s.close() 
print 'Received:', data

回答1:

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.



回答2:

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/



回答3:

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



回答4:

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).



回答5:

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