Android Open Source - Android-Chat-App Connection Establisher






From Project

Back to project page Android-Chat-App.

License

The source code is released under:

GNU General Public License

If you think the Android project Android-Chat-App listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package bb.apps.firstapp;
/*w  ww.  ja v a2  s .  c  om*/
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import android.net.NetworkInfo;
import android.util.Log;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import bb.chat.interfaces.IMessageHandler;

/**
 * @author BB20101997
 */
public class ConnectionEstablisher
{

  private SSLSocket  sock  = null;

  /**
   * @param host
   *            the host to Connect to
   * @param port
   *            the port the host is listening to
   * @param imh
   *            just needed to print out errors to the user may be removed
   *            later
   */
  public ConnectionEstablisher(String host, int port, IMessageHandler imh, NetworkInfo networkInfo)
  {

    Log.i("ConnectionEstablisher", "Trying to connect");

    if((networkInfo != null) && networkInfo.isConnected())
    {
      try
      {
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null,null,null);

                SSLSocketFactory ssf = sc.getSocketFactory();
                SSLSocket s = (SSLSocket) ssf.createSocket(host,port);
                bb.chat.util.Socket.enableAnonConnection(s);
                s.startHandshake();
                sock = s;
      }
      catch(UnknownHostException e)
      {
        System.err.println("Don't know about host " + host);
        imh.println("Could not connect to Server! \n Please check if host was spelled right!");
      }
      catch(IOException e)
      {
        System.err.println("Couldn't get I/O for the connection to " + host);
        imh.println("Could not connect to Server!");
      }
      catch(IllegalStateException e)
      {
        e.printStackTrace();
      } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            }
        }
    else
    {
      Log.e("ConnectionEstablisher", "Connectiong failed,no network");

    }

    Log.i("ConnectionEstablisher", "Connection successfull");

  }

  /**
   * @return returns the Socket that has benn created
   */
  public SSLSocket getSocket()
  {

    return sock;
  }

}




Java Source Code List

bb.apps.firstapp.AndroidMessageHandler.java
bb.apps.firstapp.ConnectionEstablisher.java
bb.apps.firstapp.MainActivity.java