具有Scala actor的客户端-服务器示例 [英] Client-Server example with Scala actors
问题描述
实现以下示例的最佳方法是什么?
What is the best way to implement the following example ?
-
Actor
server
接收个请求
,
处理它们,为每个请求创建一个新的响应
请求
,并将响应
发送回
到请求
发件人。
Actor
server
receivesRequests
, handles them, creates a newResponse
for eachRequest
and sends theResponse
back to theRequest
sender.
演员客户端
发送请求
和
收到响应
。
所有这些通信都是异步的,因此它使用 react
。
All this communication is asynchronous and hence it uses react
.
这只是一个示例,因此不应处理所有这些情况,例如服务器
都关闭,客户端
被卡住,等等。它应该简洁明了。
This is just an example and so it should not handle all those cases like server
is down, client
is stuck, etc. It should be just concise and expressive.
推荐答案
import scala.actors._
import Actor._
case class SendRequest(rid: String)
case class Request(rid: String)
case class Response(rid: String)
val server = actor {
eventloop {
case Request(rid) =>
println("Server got request [%s] from client" format(rid))
sender ! Response(rid)
}
}
}
val client = actor {
eventloop {
case SendRequest(rid) => server ! Request(rid)
case Response(rid) =>
println("Client got response [%s] from server" format(rid))
}
}
}
用法:
scala> client ! SendRequest("Hello!")
Server got request [Hello!] from client
Client got response [Hello!] from server
关于:
所有这些通信都是异步的
,因此
All this communication is asynchronous and hence it uses react.
使用 receive
的演员也是异步的。他们只是阻塞线程,等待新消息。
Actors that use receive
are also asynchronous. They just block the thread, waiting for a new messages.
这篇关于具有Scala actor的客户端-服务器示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!