import java.io.*;
import java.net.*;


public class ChatClientBase extends Thread
{
    boolean  m_bStarted = false;
    boolean  m_bRunning = false;
    
    protected Socket            m_cSocket   = null;
    protected DataInputStream   m_cInput    = null;
    protected DataOutputStream  m_cOutput   = null;
    String m_sHost = null;
    int    m_nPort = 0;
    
       
    public ChatClientBase(String sHost, int nPort)
    {
	    super("ChatClientThread");

        m_sHost = sHost;
        m_nPort = nPort;
    }
    
    protected void Start() throws UnknownHostException,IOException,Exception 
    {
        m_cSocket   = new Socket( m_sHost, m_nPort );
	    m_cOutput   = new DataOutputStream( m_cSocket.getOutputStream() );
	    m_cInput    = new DataInputStream( m_cSocket.getInputStream() );
    }
    
    public void run()
    {
	    while ( m_bRunning )
        {
	        try 
            {
		        RecvFromAndSentToServer();
	        }
	        catch (EOFException e1) 
            {
		        if ( m_bRunning )
		        {
		    	    try 
                    {
		    	        m_cInput.reset();
		    	        continue;
		    	    }
		    	    catch (IOException e11) 
                    {
		    	        if ( TryToReconnect() )
		    		        continue;
		    	    }
		        }
		        return;
	        }
	        catch (IOException e2) 
            {
		        if ( m_bRunning )
		        {
		    	    if ( TryToReconnect() )
		    	        continue;
		        }
		        return;
	        }
	        catch (Exception e3) 
            {
                //ignore
		        continue;
	        }
        }
    }
    
    private boolean TryToReconnect()
    {
	    try 
        {
	        synchronized ( m_cInput ) 
            {
		        synchronized ( m_cOutput ) 
                {
	                m_cSocket = new Socket( m_sHost, m_nPort );
	                m_cOutput = new DataOutputStream( m_cSocket.getOutputStream() );
	                m_cInput  = new DataInputStream(  m_cSocket.getInputStream()  );
		        }
	        }
	    }
	    catch (Exception e) 
        {
	        ConnectionLost();
	        return false;
	    }

	    return true;
    }
    
    private void RecvFromAndSentToServer() throws IOException
    { 
        RecvFromServer();
        SendToServer();
    }
    protected void RecvFromServer() throws IOException
    {
        
    }
    
    protected void SendToServer()	throws IOException
    {
	    m_cOutput.flush();
    }
    
    protected void ConnectionLost()
    {
        
    }
}

