可以在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");
}
}