具有Scala actor的客户端-服务器示例 [英] Client-Server example with Scala actors

查看:141
本文介绍了具有Scala actor的客户端-服务器示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现以下示例的最佳方法是什么?

What is the best way to implement the following example ?


  • Actor server 接收个请求
    处理它们,为每个请求创建一个新的响应
    请求,并将响应发送回
    请求发件人。

  • Actor server receives Requests, handles them, creates a new Response for each Request and sends the Response back to the Request 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆