Package com.entertailion.java.caster

Source Code of com.entertailion.java.caster.RampWebSocketClient

/*
* Copyright (C) 2013 ENTERTAILION LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.entertailion.java.caster;

import java.net.URI;
import java.nio.ByteBuffer;
import java.util.LinkedList;

import org.java_websocket.WebSocketImpl;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.handshake.ServerHandshake;

/*
* Web socket client for RAMP commands
* https://github.com/TooTallNate/Java-WebSocket
*
* @author leon_nicholls
*/
public class RampWebSocketClient extends WebSocketClient {

  private static final String LOG_TAG = "RampWebSocketClient";

  private RampWebSocketListener rampWebSocketListener;

  // Queue messages until the connection is ready
  private LinkedList<String> messageQueue = new LinkedList<String>();

  private boolean ready;

  public RampWebSocketClient(URI uri, RampWebSocketListener rampWebSocketListener) {
    super(uri, new Draft_17());
    this.rampWebSocketListener = rampWebSocketListener;
    WebSocketImpl.DEBUG = Log.getVerbose();
  }

  @Override
  public void onMessage(String message) {
    rampWebSocketListener.onMessage(message);
  }

  @Override
  public void onMessage(ByteBuffer blob) {
    getConnection().send(blob);
  }

  @Override
  public void onError(Exception ex) {
    rampWebSocketListener.onError(ex);
  }

  @Override
  public void onOpen(ServerHandshake handshake) {
    ready = true;
    for (String msg : messageQueue) {
      super.send(msg);
    }
    messageQueue.clear();
    rampWebSocketListener.onOpen(handshake);
  }

  @Override
  public void onClose(int code, String reason, boolean remote) {
    rampWebSocketListener.onClose(code, reason, remote);
  }

  @Override
  public void send(String message) {
    Log.d(LOG_TAG, "message=" + message);
    if (ready) {
      for (String msg : messageQueue) {
        super.send(msg);
      }
      messageQueue.clear();
      super.send(message);
    } else {
      messageQueue.add(message);
    }
  }

}
TOP

Related Classes of com.entertailion.java.caster.RampWebSocketClient

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.