CS-465 / testEcho / Client / src / echo / EchoClientThread.java
EchoClientThread.java
Raw
package echo;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * Simple EchoThread reading chars from user and sending them to EchoServer
 * 
 * @author wolfdieterotte
 */
public class EchoClientThread extends Thread
{

    Socket serverConnection = null;
    
    DataInputStream fromServer = null;
    DataOutputStream toServer = null;
    
    // for reading from stdin
    InputStreamReader userInput = new InputStreamReader(System.in);

    
    /**
     * Constructor, initializes the connection to EchoServer and opens up stdin
     * 
     * @param serverIP Server IP
     * @param serverPort Server port
     */
    public EchoClientThread(String serverIP, int serverPort) 
    {
        // open server socket
        try
        {
            serverConnection = new Socket(serverIP, serverPort);
            fromServer       = new DataInputStream (serverConnection.getInputStream ());
            toServer         = new DataOutputStream(serverConnection.getOutputStream());
        }
        catch(IOException ex)
        {
            Logger.getLogger(EchoClient.class.getName()).log(Level.SEVERE, "Cannot connect to server", ex);
            System.exit(1);
        }
        
        // open up stdin
        userInput = new InputStreamReader(System.in);
    }

    
    /**
     * Implementation interface Runnable.
     * Read chars from user, send to server and read them back in.
     * Terminates, when 'q' is entered
     */
    @Override
    public void run() 
    {
        char charFromUser = 0;
        char charFromServer = 0;
        
        // forever
        while (true) {
        
            try {
                // read char from user
                charFromUser = (char) userInput.read();
            } catch (IOException ex) {
                Logger.getLogger(EchoClientThread.class.getName()).log(Level.SEVERE, null, ex);
            }

            // write char to EchoServer
            try {
                toServer.writeByte(charFromUser);
            } catch (IOException e) {
            }
            
            // read char back from EchoServer
            try {
                charFromServer = (char) fromServer.readByte();
            } catch (IOException e) {
            }
            
            // print char received on stdout
            System.out.print(charFromServer);
            
            // terminate, if q was received (and entered before to begin with)
            if(charFromServer == 'q')
            {
                break;
            }
        }

        // close connection to server
        try {
            serverConnection.close();
        } catch (IOException e) {
        }
    }
}