package comm.server;

import android.os.Build;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;	 

public class MainActivity extends Activity {
		 
  private ServerSocket serverSocket;
  private String str;
  Handler textHandler;
  Thread serverThread = null;
  private TextView textView;
  public static final int portNumber = 2014;
	
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
	textView = (TextView) findViewById(R.id.text1);
	textHandler = new Handler();
    new Thread(new ServerThread()).start();
  }
	
  @Override
  protected void onStop() {
    super.onStop();
    try {
      serverSocket.close();	        
    } catch (IOException e) {
      e.printStackTrace();
	}
  }
  
  //Inner class
  class ServerThread implements Runnable {
    public void run() {
      Socket commSocket = null;
      try {
	    serverSocket = new ServerSocket(portNumber);
	  } catch (IOException e) {
	    e.printStackTrace();
      }
      while (!Thread.currentThread().isInterrupted()) {
	    try {
	      commSocket = serverSocket.accept();
	      BufferedReader input = new BufferedReader (
	        new InputStreamReader( commSocket.getInputStream() ));
	      while ( ( str = input.readLine() )  != null ) 
	    	textHandler.post(new ShowText ());
        } catch (IOException e) {
	       e.printStackTrace();
	    }
      }
    }
  } //ServerThread

  // Inner class
  class ShowText implements Runnable {	
    @Override
	public void run() {
	  textView.setText(textView.getText().toString()+"Client said: "+ str + "\n");
	}
  } //ShowText
} //MainActivity