我尝试在netty中发送特定用户的消息。为此,我需要将用户名和CahnnelHandlerContext存储在Arralist中,我可以检查用户是否连接到服务器并获取特定用户的ChannelhandlerContext。
你能告诉我最好的做法吗?
这里是我处理连接的服务器的一些代码:
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import java.util.ArrayList;
import messages.SecureMessageServerClientMessage;
import messages.SecureMessageServerUser;
/**
* Handles a server-side channel.
*/
public class SecureChatServerHandler extends SimpleChannelInboundHandler<SecureMessageServerClientMessage> {
protected ArrayList<SecureMessageServerUser> userList = new ArrayList();
@Override
public void channelActive(final ChannelHandlerContext ctx) {
// Once session is secured, send a greeting and register the channel to the global channel
// list so the channel received the messages from others.
ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
new GenericFutureListener<Future<Channel>>() {
@Override
public void operationComplete(Future<Channel> future) throws Exception {
userList.add(new SecureMessageServerUser("", ctx));
}
});
}
@Override
public void channelRead0(ChannelHandlerContext ctx, SecureMessageServerClientMessage msg ) throws Exception {
switch(msg.getType()){
case 0:
ctx.writeAndFlush(new SecureMessageServerClientMessage(0, this.userList));
break;
case 1:
System.out.println("TestMessage Typ 1");
String empfaenger, sender, message;
sender=msg.getSender();
empfaenger = msg.getEmpfaenger();
message = msg.getMessage();
for (SecureMessageServerUser user : this.userList) {
System.out.println(user.getUserName());
// if (user.getUserName().equals(empfaenger)) {
// user.getCtx().writeAndFlush(new SecureMessageServerClientMessage(1, message, sender));
// }
}
Thread.sleep(1000);
break;
case 2://User aus Liste löschen und alle Resorucen freigeben
case 3: //Liste mit allen Benutzern an Clienten senden
ctx.writeAndFlush(new SecureMessageServerClientMessage(0, this.userList));
break;
default:
System.out.println("Unbekannter Nachrichtentyp");
}
}
@Override
public void channelUnregistered(final ChannelHandlerContext ctx) {
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
答案 0 :(得分:2)
我认为将它存储在ConcurrentMap中最好使用username作为键,使用ChannelHandlerContext作为值。另请注意,这与Netty没有任何关系,更多的是使用什么数据结构来存储从键到值的映射。