package PortForwarder;
import java.net.*;
import  java.io.*;

// Written by Sean R. Owens, sean at guild dot net, released to the
// public domain.  Share and enjoy.  Since some people argue that it is
// impossible to release software to the public domain, you are also free
// to use this code under any version of the GPL, LPGL, or BSD licenses,
// or contact me for use of another license.
// http://darksleep.com/player
public class JustListenHandler implements Runnable{
    
    Socket inSocket = null;
    Thread myThread = null;
    private BufferedInputStream socketInput = null;
    private PrintWriter socketOutput = null;

    public JustListenHandler(Socket inSocket) {
        this.inSocket = inSocket;
        try {
            socketInput = new BufferedInputStream(inSocket.getInputStream());
            socketOutput = new PrintWriter(inSocket.getOutputStream(), true);
        }
        catch(Exception e) {
            System.err.println("Exception creating i/o streams:"+e);
            e.printStackTrace();
        }
        
        myThread = new Thread(this);
        myThread.start();
    }

    public void run() {
        int bytesRead=0;
        int bufLen = 10000;
        byte buf[]= new byte[bufLen];

        while(true) {

            try {
                bytesRead = socketInput.read(buf,0,bufLen);
                if(bytesRead > 0) {
                    String readString = new String(buf,0,bytesRead);
                    System.err.println("read:"+readString);
                    socketOutput.print("received:"+readString);
                    socketOutput.flush();
                }
                else if(bytesRead < 0) {
                    System.err.println("Socket closed on us:"+inSocket);
                    return;
                }
                else {
                    System.err.println("Socket did something weird - returned 0 bytes read instead of blocking:"+inSocket);
                    return;
                }
            }
            catch(Exception e) {
                System.err.println("Exception creating serverSocket:"+e);
                e.printStackTrace();
            }

        }
    }

}