private void notifyChannelsDisconnected() {
   Set<Channel> channelSet = channelIndex.keySet();
   Iterator<Channel> iterator = channelSet.iterator();
   while (iterator.hasNext()) {
     Channel channel = iterator.next();
     channel.onDisconnect();
   }
 }
  @Override
  public void onClose(Channel fromChannel) {
    // if we're allready disconnected we can ignore
    if (isDisconnected()) return;

    // check if all channels are disconnected and if so disconnect from the socket
    for (Channel channel : channels.values()) {
      if (channel.isStarted()) return;
    }
    Logger.log(
        TAG,
        String.format(Locale.US, "%s disconnect from socket", Thread.currentThread().getName()));
    disconnect();
  }
 /** Creates a channel for the bucket. Starts the websocket connection if not connected */
 @Override
 public Channel buildChannel(Bucket bucket) {
   // create a channel
   Channel channel = new Channel(mExecutor, appId, sessionId, bucket, mSerializer, this);
   int channelId = channels.size();
   channelIndex.put(channel, channelId);
   channels.put(channelId, channel);
   // If we're not connected then connect, if we don't have a user
   // access token we'll have to hold off until the user does have one
   if (!isConnected() && bucket.getUser().hasAccessToken()) {
     connect();
   } else if (isConnected()) {
     channel.onConnect();
   }
   return channel;
 }
 public void onMessage(String message) {
   scheduleHeartbeat();
   int size = message.length();
   String[] parts = message.split(":", 2);
   ;
   if (parts[0].equals(COMMAND_HEARTBEAT)) {
     heartbeatCount = Integer.parseInt(parts[1]);
     return;
   } else if (parts[0].equals(COMMAND_LOG)) {
     logLevel = Integer.parseInt(parts[1]);
     return;
   }
   try {
     int channelId = Integer.parseInt(parts[0]);
     Channel channel = channels.get(channelId);
     channel.receiveMessage(parts[1]);
   } catch (NumberFormatException e) {
     Logger.log(TAG, String.format(Locale.US, "Unhandled message %s", parts[0]));
   }
 }
 @Override
 public void onLog(Channel channel, int level, CharSequence message) {
   try {
     JSONObject log = new JSONObject();
     log.put(COMMAND_LOG, message);
     log.put(BUCKET_NAME_KEY, channel.getBucketName());
     log(level, log);
   } catch (JSONException e) {
     Logger.log(TAG, "Unable to send channel log message", e);
   }
 }