Package connection.server

Source Code of connection.server.ConnectionManager

package connection.server;


import java.net.InetSocketAddress;
import java.util.ArrayList;

import main.settings.Settings;

import common.connection.client.AbstractClientSideConnector;
import common.connection.client.ConnectionAttempt;
import common.connection.client.ConnectionAttempterInterface;

import ui.misc.MessageBox;


public class ConnectionManager implements ConnectionManagerInterface,
    ConnectionAttempterInterface
{
  private volatile ServerConnection connection;
  private volatile boolean connected;

  private ArrayList<ConnectionStateListener> listeners;

  public ConnectionManager()
  {
    connected = false;
    listeners = new ArrayList<ConnectionStateListener>();
  }

  public synchronized void addListener(ConnectionStateListener listener)
  {
    listeners.add(listener);
  }

  public synchronized void connect(String host, int port)
  {
    disconnect();

    for (ConnectionStateListener listener : listeners)
    {
      listener.onConnecting();
    }

    new ConnectionAttempt(this, new InetSocketAddress(host, port),
        Settings.connection.security.to_server);
  }

  public synchronized void disconnect()
  {
    if (!connected)
    {
      return;
    }

    connected = false;
    connection.terminate();
    connection = null;
  }

  public boolean isConnected()
  {
    return connected;
  }

  public ServerConnection getConnection()
  {
    if (!connected)
    {
      throw new IllegalStateException();
    }

    return connection;
  }

  public AbstractClientSideConnector getConnector()
  {
    return new ServerConnector(this);
  }

  public void notifyConnected(ServerConnection connection)
  {
    this.connection = connection;
    connected = true;

    for (ConnectionStateListener listener : listeners)
    {
      listener.onConnected(connection);
      listener.updateConnectionState(true);
    }
  }

  public synchronized void notifyFailure()
  {
    for (ConnectionStateListener listener : listeners)
    {
      listener.onFailed();
    }

    MessageBox.showError("Connection failed.", "Connection Failed");
  }

  public synchronized void notifyDisconnection()
  {
    connected = false;
    connection = null;

    for (ConnectionStateListener listener : listeners)
    {
      listener.onDisconnected();
      listener.updateConnectionState(false);
    }
  }

}
TOP

Related Classes of connection.server.ConnectionManager

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.