akka java tcp聊天室
我试图在doc中扩展关于TCP的代码,以创建一个简单的聊天室,简单地说,几个客户端连接到服务器,一个客户端发送字符串,服务器向所有客户端广播字符串…我编写的代码如下所示,它不起作用,有人能告诉我为什么吗akka java tcp聊天室,java,tcp,akka,Java,Tcp,Akka,我试图在doc中扩展关于TCP的代码,以创建一个简单的聊天室,简单地说,几个客户端连接到服务器,一个客户端发送字符串,服务器向所有客户端广播字符串…我编写的代码如下所示,它不起作用,有人能告诉我为什么吗 程序行为错误,例如两个客户端连接到服务器,一个发送消息,然后发送方返回两条消息,另一个什么也得不到 Main.java public class Main { public static void main(String[] args) { akka.Main.main(new St
程序行为错误,例如两个客户端连接到服务器,一个发送消息,然后发送方返回两条消息,另一个什么也得不到 Main.java
public class Main {
public static void main(String[] args) {
akka.Main.main(new String[] { Server.class.getName()});
}
}
Server.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());
}
}
}
Notification.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参与者分配了
Notification.sender
您需要做的是在
服务器中处理已连接的时,将发送方传递给SimplisticHandler
。每个SimplisticHandler
始终向自己的tcp参与者写入信息。您为发送消息的tcp参与者分配了Notification.sender
您需要做的是在服务器中处理已连接的时,将发送方传递给SimplisticHandler
。每个SimplisticHandler
都要写自己的tcp参与者。介意提供更多关于它为什么不起作用的细节吗?(错误消息、错误行为等)。程序行为错误,例如,两个客户端连接到服务器,一个发送消息,然后发送者返回两条消息,另一个什么也得不到……介意提供更多有关它为什么不工作的详细信息吗?(错误消息、错误行为等)。程序行为错误,例如,两个客户端连接到服务器,一个发送消息,然后发送方返回两条消息,另一个什么也得不到。。。