gpt4 book ai didi

scala - 如何在 Akka 远程参与者之间发送消息?

转载 作者:行者123 更新时间:2023-12-04 06:10:30 24 4
gpt4 key购买 nike

我想建一个非常简单的聊天应用程序,它应该可以在没有使用 Akka 远程角色的中央服务器的情况下工作。

我基本上想用 IP 地址 A 启动应用程序的一个实例。
然后我想用 IP 地址 A 启动应用程序的一个实例,并告诉它远程实例位于 IP 地址 B。

我将如何设置它? Akka 文档通常只涵盖客户端/服务器用例,甚至基本的东西也让我完全困惑,例如。 G。在哪里使用 Actor.actorOf对比 Actor.register对比 Actor.remote .

我的代码目前看起来像这样:

import collection.mutable.{ArrayBuffer, HashSet}
import akka.actor.Actor

sealed trait Event
/** Join tells the peer that there is a new peer and
* requests a list of known peers and messages. */
case class Join(user: String, ipAddress: String) extends Event
/** Join tells the peer that there is a new peer. */
case class Register(user: String, ipAddress: String) extends Event
case class Leave(user: String, ipAddress: String) extends Event
case object GetChatLog extends Event
case object GetPeers extends Event
case class ChatLog(log: Seq[Message]) extends Event
case class Peers(peers: Seq[Peer]) extends Event
case class Message(sender: String, time: Long, message: String) extends Event

class ChatPeer(val name: String, ipAddress: String) extends Actor {
val chat = Actor.remote.actorFor("chat:service", ipAddress, 2552) //This is not what I want...
val messages = ArrayBuffer[Message]()
val peers = HashSet[Peer]()

def join = {
(chat ? Join(name, ipAddress)).as[(Seq[Peer], Seq[Message])]
}

def register = chat ! Register(name, ipAddress)

def leave = chat ! Leave(name, ipAddress)

def send(message: String) = {
val msg = Message(name, System.currentTimeMillis(), message)
messages += msg
chat ! msg
}

def getMessages = (chat ? GetChatLog).as[ChatLog]
.getOrElse(throw new Exception("Couldn't get the chat log from ChatServer"))

def getPeers = (chat ? GetPeers).as[Peers]
.getOrElse(throw new Exception("Couldn't get the peers from ChatServer"))


def receive = {
case msg@Message(from, time, message) =>
println(msg)
messages += msg

case GetChatLog =>
self reply messages

case GetPeers =>
self reply peers

case Join =>
peers += Peer(name, ipAddress)
self reply ((peers, messages))

case Register(user, ipAddress) =>
peers += Peer(user, ipAddress)

case Leave(user, ipAddress) =>
peers -= Peer(user, ipAddress)

}
}

case class Peer(name: String, ipAddress: String)

最佳答案

不确定我是否理解您从示例代码中想要的内容。

我认为,如果你想制作一个没有专用服务器的版本,那么基本上两个对等点都必须启动并注册一个远程服务器

remote.start("localhost", somePort).register("chat-main", actorOf[ChatMain])

然后尝试连接到对方的服务器
val otherActor = remote.actorFor("chat-main", otherHost, somePeer)

基本上,您必须同时创建对等服务器和客户端。设置的其余部分是一些协商和聊天逻辑,但从技术上讲,它并不比 Akka 网站上的简单示例复杂多少。

关于scala - 如何在 Akka 远程参与者之间发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7844324/

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