gpt4 book ai didi

java - akka java tcp 聊天室

转载 作者:可可西里 更新时间:2023-11-01 02:54:06 29 4
gpt4 key购买 nike

我试图扩展doc中关于TCP的代码来制作一个简单的聊天室,简单地说,几个客户端连接到服务器,一个客户端发送一个字符串,服务器将字符串广播给所有客户端......我写的代码显示下面,它不起作用,有人可以告诉为什么吗?

程序运行错误,假设有 2 个客户端连接到服务器,一个发送一条消息,然后发送者收到 2 条消息,另一个什么也得不到...

主.java

public class Main {
public static void main(String[] args) {
akka.Main.main(new String[] { Server.class.getName()});
}
}

服务器.java

public class Server extends UntypedActor {

final ActorRef manager = Tcp.get(getContext().system()).manager();

public static Props props(ActorRef manager) {
return Props.create(Server.class, manager);
}

@Override
public void preStart() throws Exception {
final ActorRef tcp = Tcp.get(getContext().system()).manager();
tcp.tell(TcpMessage.bind(getSelf(), new InetSocketAddress("0.0.0.0", 8888), 100), getSelf());
}

@Override
public void onReceive(Object msg) throws Exception {
if (msg instanceof Bound) {
manager.tell(msg, getSelf());

} else if (msg instanceof CommandFailed) {
getContext().stop(getSelf());

} else if (msg instanceof Connected) {
final Connected conn = (Connected) msg;
manager.tell(conn, getSelf());
final ActorRef handler = getContext().actorOf(Props.create(SimplisticHandler.class));
getContext().system().eventStream().subscribe(handler, Notification.class);
getSender().tell(TcpMessage.register(handler), getSelf());
}
}

}

SimplisticHandler.java

public class SimplisticHandler extends UntypedActor {
@Override
public void onReceive(Object msg) throws Exception {
if (msg instanceof Received) {

final ByteString data = ((Received) msg).data();
System.out.println(data);
getContext().system().eventStream().publish(new Notification(getSender(), getSelf(), 1, data));

} else if (msg instanceof ConnectionClosed) {

getContext().stop(getSelf());

} else if (msg instanceof Notification) {

Notification noti = (Notification)msg;
// TODO while the below statement don't broadcast ?
if (noti.id == 1)
noti.sender.tell(TcpMessage.write((ByteString)(noti.obj)), getSelf());

}
}
}

通知.java

public class Notification {
public final ActorRef sender;
public final ActorRef receiver;
public final int id;
public final Object obj;

public Notification(ActorRef sender, ActorRef receiver, int id, Object obj) {
this.sender = sender;
this.receiver = receiver;
this.id = id;
this.obj = obj;
}
}

最佳答案

您为发送消息的 tcp actor 分配了 Notification.sender

您需要做的是在 Server 中处理 Connected 时,将 sender 传递给 SimplisticHandler。并且每个 SimplisticHandler 总是写入它们自己的 tcp actor。

关于java - akka java tcp 聊天室,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35168660/

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