package com.example.robot;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
 
public class MainActivity extends Activity
{
		private TextView tvServerMessage;
 
		Button button1;
 
		@Override
		protected void onCreate(Bundle savedInstanceState) 
		{
				super.onCreate(savedInstanceState);
				setContentView(R.layout.activity_main);
				tvServerMessage = (TextView) findViewById(R.id.textView2);
  
				button1 = (Button) findViewById(R.id.button1);
  
				//Create an instance of AsyncTask
				ClientAsyncTask clientAST = new ClientAsyncTask();
				//Pass the server ip, port and client message to the AsyncTask
  clientAST.execute(new String[] { "192.168.1.24", "8000","Hello from client" });
 
		
  button1.setOnClickListener(new View.OnClickListener() {
	 	public void onClick(View v) {
	 		String toto = "454";
	 	}
	 });
		
}
 
 
 
 
 
 
/**
 * AsyncTask which handles the communication with the server 
 */
 class ClientAsyncTask extends AsyncTask<String, Void, String> {
  @Override
  protected String doInBackground(String... params) {
   String result = null;
   try {
    //Create a client socket and define internet address and the port of the server
    Socket socket = new Socket(params[0],
      Integer.parseInt(params[1]));
    //Get the input stream of the client socket
    InputStream is = socket.getInputStream();
    //Get the output stream of the client socket
    PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
    //Write data to the output stream of the client socket
    out.println(params[2]); 
    //Buffer the data coming from the input stream
    BufferedReader br = new BufferedReader(
      new InputStreamReader(is));
    //Read data in the input buffer
    result = br.readLine();
    //Close the client socket
    socket.close();
   } catch (NumberFormatException e) {
    e.printStackTrace();
   } catch (UnknownHostException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
   return result;
  }
  @Override
  protected void onPostExecute(String s) {
   //Write server message to the text view
   tvServerMessage.setText(s);
  }
 }
}