可以在handler处理函数中,客户端主动注册一个id(例如设备imei号),通过下面的类似实现,放入一个HashMap中。
然后就可以实现发消息给特定client id了。
public static synchronized int getClientId(int clientId) {
Channel channel = mChannels.get("" + clientId);
if (channel != null) {
logger.info("getClientId: alreay exist, clientId=" + clientId);
return clientId;
} else {
mClientIdCounter++;
logger.info("getClientId: getClientId=" + mClientIdCounter);
return mClientIdCounter;
}
}
public static synchronized void addClient(String clientId, Channel sc) {
Channel channel = mChannels.get(clientId);
if (channel != null) {
logger.info("addClient: alreay in, clientId=" + clientId);
} else {
logger.info("addClient: add new, clientId=" + clientId);
mChannels.put(clientId, sc);
}
}
public static synchronized void removeClient(String clientId) {
Channel channel = mChannels.get(clientId);
if (channel != null) {
mChannels.remove(clientId);
logger.info("removeClient: removed, clientId=" + clientId);
} else {
logger.info("removeClient: not found, clientId=" + clientId);
}
}
private static class LoggingListener implements ChannelFutureListener {
@Override
public void operationComplete(ChannelFuture future) {
logger.info("LoggingListener: sendMsgToClient done");
}
}
public static void sendMsgToClient(String clientId, Object object) {
Channel channel = mChannels.get(clientId);
if (channel != null && channel.isActive()) {
ChannelPromise promise = channel.newPromise();
promise.addListener(new LoggingListener());
channel.writeAndFlush(object, promise);
logger.info("sendMsgToClient: run done");
}
}