/*
 * Copyright (C) 2013 Jeremiah ONeal <joneal@nuaitp.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package receiver;

import java.net.*;
import java.io.*;

/**
 *
 * @author Jeremiah ONeal <joneal@nuaitp.net>
 */
public class Receiver implements Runnable{
    Thread answering;
    Socket socket;
    
    public Receiver(String platform)
    {
        StartController("----");
    }
    public void StartController(String platform)
    {
        int port = Integer.parseInt(data.Data.connectionport.trim());
        try
        {
            ServerSocket srv = new ServerSocket(port);
            while(true)
            {
                try
                {
                    Thread.sleep(5000);
                    answering = new Thread(this, "Answers incoming connections");
                
                    socket = srv.accept();
                    answering.start();
                }
                catch(IOException e)
                {
                }
                catch (InterruptedException e)
                {
                }
            }
        }
        catch(IOException e)
        {
        }
        
    }
    public void run()
    {
        try
        {
            BufferedReader rd = new BufferedReader (new InputStreamReader(socket.getInputStream()));
            BufferedWriter wr = new BufferedWriter (new OutputStreamWriter(socket.getOutputStream()));
            wr.write("Connected!\n");
            wr.flush();
            String str = "";
            while(str != null)
            {
                Thread.sleep(1000);
                try
                {
                    str = rd.readLine();
                }
                catch(IOException e)
                {
                }
                wr.write("You said " + str + "\n");
                wr.flush(); //you can use str.equals.
                }
            }
        catch (IOException e)
        {
        }
        catch(InterruptedException e)
        {
        }
    }
}
