tkb*_*elt 16 sockets multithreading scala actor akka
使用Scala和Akka IO有一种方法可以让一个Actor严格用于监听,然后在建立连接时创建一个新的actor,然后负责该Socket(阅读,写作等)?
到目前为止,我有这个.问题是Server actor正在接收数据.我想将套接字的所有权转移到新创建的Client actor,以便它接收与套接字相关的任何消息.谁知道怎么做?
编辑:添加解决方案.我只需要将ActorRef传递给accept的curried参数
import akka.actor._
import akka.actor.IO.SocketHandle
import java.net.InetSocketAddress
/**
* Purpose:
* User: chuck
* Date: 17/01/13
* Time: 5:37 PM
*/
object Main {
class Server extends Actor {
override def preStart() {
IOManager(context.system) listen new InetSocketAddress(3333)
}
def receive = {
case IO.NewClient(server) =>
val client = context.actorOf(Props(new Client()))
server.accept()(client)
println("Client accepted")
case IO.Read(socket, bytes) =>
println("Server " + bytes)
}
}
class Client() extends Actor {
def receive = {
case IO.Read(socket, bytes) =>
println("Client " + bytes)
case IO.Closed(socket, reason) =>
println("Socket closed " + reason)
}
}
def main(args: Array[String]) {
val system = ActorSystem()
system.actorOf(Props(new Server))
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
为了让答案更加明显:
来自Akka文档:ServerHandle
def accept ()(implicit socketOwner: ActorRef): SocketHandle
Run Code Online (Sandbox Code Playgroud)
应该接收与 SocketChannel 关联的事件的socketOwner ActorRef。当前 Actor 的 ActorRef 将被隐式使用。
如果没有向柯里化参数传递任何内容(仅调用server.accept()),则当前 Actor(服务器)将从 SocketChannel 接收事件。然而,正如方法签名所示,您可以将 ActorRef 传递给柯里化参数,以便 SocketChannel 上发生的事件将由这个新 Actor 处理。
让我们看看问题所有者添加的解决方案:
def receive = {
case IO.NewClient(server) =>
val client = context.actorOf(Props(new Client()))
server.accept()(client) // Transferring ownership of the socket to a new Actor
println("Client accepted")
case IO.Read(socket, bytes) =>
println("Server " + bytes)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2289 次 |
| 最近记录: |