Scala相当于python echo服务器/客户端的例子?

时间:2011-06-20 17:15:51

标签: python scala echo

scala中的所有“服务器”示例都使用actor,反应器等......

有人可以告诉我如何写一个死的简单回显服务器和客户端,就像下面的ServerClient的python示例一样:

# 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

5 个答案:

答案 0 :(得分:30)

您可以在标准库中执行以下操作:

// 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()

如果您不介意使用额外的库,可能需要Finagle

答案 1 :(得分:3)

我刚刚撰写了一篇关于使用Akka IO和Iteratees创建基于命令的简单套接字服务器的博文。

也许它可能会引起人们的兴趣。

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

答案 2 :(得分:2)

您必须使用Java套接字。我找到了一个很好的Scala套接字服务器/客户端示例:http://www.scala-lang.org/node/55

答案 3 :(得分:0)

您可以使用netty java库。以下是Scala中的示例用法:

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

通常您需要使用Java Socket API。在this example中使用了Java Socket API,但是整个服务器都包含在Actor中,以便在单独的线程中处理客户端而不是阻塞接受器线程(与通常在Java中执行的操作相同,但是您将使用线程直接地)。

答案 4 :(得分:0)

Josh Suereth最近发布了example of an NIO echo server using scalaz Iteratees。需要scalaz

相关问题