gpt4 book ai didi

multithreading - 每个 Actor 的 Akka 套接字

转载 作者:行者123 更新时间:2023-12-03 15:02:56 25 4
gpt4 key购买 nike

将 Scala 与 Akka IO 一起使用是否有办法让 Actor 严格用于监听,然后在建立连接时创建一个新的 Actor,然后负责该 Socket(读取、写入等)?

到目前为止,我有这个。问题是服务器参与者正在接收数据。我想将套接字的所有权转移给新创建的客户端参与者,以便它接收与套接字相关的任何消息。有谁知道该怎么做?

编辑:添加解决方案。我只需要将 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))
}

}

谢谢!

最佳答案

为了让答案更明显:

来自 Akka documentation对于 ServerHandle :

def accept ()(implicit socketOwner: ActorRef): SocketHandle

socketOwner ActorRef that should receive events associated with the SocketChannel. The ActorRef for the current Actor will be used implicitly.



如果没有向 curried 参数传递任何内容(仅调用 server.accept()),则当前 Actor(服务器)将从 SocketChannel 接收事件。然而,正如方法签名所暗示的,您可以将 ActorRef 传递给 curried 参数,以便 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)
}

关于multithreading - 每个 Actor 的 Akka 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14408273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com