title: Optimizing Java Socket Sending Android to PC
body: <p>I need Your help!</p>
  
  <p>So I got this app on an Android device, in which I get data from the accelerometer, and button presses which get this data to an edittext, and sets listeners on the edittextes.</p>
  
  <p>When it's changed, there's a functions that creates a socket, sends data, and closes the socket. </p>
  
  <p>Then I have a server app on my computer, in which I create serversockets, and create two threads that are waiting for <code>serversocket.accept()</code> that gets the data and put it into texbox. Simple as that. </p>
  
  <p>I'm glad that I got it working anyway :-) but the point is, it's not working so well. I believe that whole communication is bad and not optimized. It sends data well, but often freezes, then unfreezes and sends quickly all previous data and so on. </p>
  
  <p>I'm sorry for my bad code, but can someone please take a good look on this, and propose what I should change and how I could make it work more smooth and stable? :-(</p>
  
  <p>Here's the Client code:</p>
  
  <pre><code>package com.test.klienttcp;
  
  //import's...
  
  public class Klient extends Activity implements SensorListener {
  
  
  final String log = "Log";
  EditText textOut;
  EditText adres;
  EditText test;
  EditText gazuje;
  TextView textIn;
  TextView tekst;
  TextView dziala;
  String numer = null;
  float wspk = 0; // wspolczynniki kalibracji
  float wychylenietmp = 0;
  float wychylenie = 0;
  int tmp = 0;
  int i = 0;
  boolean wysylaj = false;
  
  SensorManager sm = null;
  
  
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
  
       textOut = (EditText)findViewById(R.id.textout);
       adres = (EditText)findViewById(R.id.adres);
       gazuje = (EditText)findViewById(R.id.gazuje);
       Button kalibracja = (Button)findViewById(R.id.kalibracja);
       Button polacz = (Button)findViewById(R.id.polacz);
       Button gaz = (Button)findViewById(R.id.gaz);
       Button hamulec = (Button)findViewById(R.id.hamulec);
       kalibracja.setOnClickListener(kalibracjaOnClickListener);
       polacz.setOnClickListener(polaczOnClickListener);
       gaz.setOnTouchListener(gazOnTouchListener);
       hamulec.setOnTouchListener(hamulecOnTouchListener);
       sm = (SensorManager) getSystemService(SENSOR_SERVICE);
  
       //text listener steering
       textOut.addTextChangedListener(new TextWatcher() {
           public void afterTextChanged(Editable s) {
           }
           public void beforeTextChanged(CharSequence s, int start, int count, int after) {
           }
           public void onTextChanged(CharSequence s, int start, int before, int count) {
               if(wysylaj)
               {
                   Wyslij();
               }
           }
       });
  
     //text listener for throttle         
     gazuje.addTextChangedListener(new TextWatcher() {
           public void afterTextChanged(Editable s) {
           }
           public void beforeTextChanged(CharSequence s, int start, int count, int after) {
           }
           public void onTextChanged(CharSequence s, int start, int before, int count) {
               if(wysylaj)
               {
                   Gaz();
               }
           }
       });
  
   }
  
   Button.OnClickListener polaczOnClickListener
   = new Button.OnClickListener(){
  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   if(wysylaj==false)
   {
       wysylaj = true;
   }
   else
   {
       wysylaj = false;
   }
  }};
  
  //throttle button handler
  Button.OnTouchListener gazOnTouchListener
  = new Button.OnTouchListener(){
  @Override
  public boolean onTouch(View arg0, MotionEvent event) {
      // TODO Auto-generated method stub
      if(event.getAction() == MotionEvent.ACTION_DOWN) {
          gazuje.setText("1");
      } else if (event.getAction() == MotionEvent.ACTION_UP) {
          gazuje.setText("0");
      }
      return false;
  }};
  
  //brake button handler
  Button.OnTouchListener hamulecOnTouchListener
  = new Button.OnTouchListener(){
  @Override
  public boolean onTouch(View arg0, MotionEvent event) {
      // TODO Auto-generated method stub
      if(event.getAction() == MotionEvent.ACTION_DOWN) {
          gazuje.setText("2");
      } else if (event.getAction() == MotionEvent.ACTION_UP) {
          gazuje.setText("0");
      }
      return false;
  }};
  
  
   //sensor handler
   public void onSensorChanged(int sensor, float[] values) {
          synchronized (this) {
              if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
                  wychylenie = values[0] * 10;
                  tmp = Math.round(wychylenie);
                  wychylenie = tmp / 10;
                  if(wychylenie != wychylenietmp)
                  {
                  textOut.setText(Float.toString(wychylenie - wspk));
                  wychylenietmp = wychylenie;
                  }
              }
          }
      }
  
   public void onAccuracyChanged(int sensor, int accuracy) {
          Log.d(log, "onAccuracyChanged: " + sensor + ", accuracy: " + accuracy);
  
      }
  
   @Override
      protected void onResume() {
          super.onResume();
          sm.registerListener(this, SensorManager.SENSOR_ORIENTATION
                  | SensorManager.SENSOR_ACCELEROMETER,
                  SensorManager.SENSOR_DELAY_NORMAL);
      }
  
      @Override
      protected void onStop() {
          sm.unregisterListener(this);
          super.onStop();
      }
  
      //callibration handler
  
       Button.OnClickListener kalibracjaOnClickListener
       = new Button.OnClickListener(){
      @Override
      public void onClick(View arg0) {
       // TODO Auto-generated method stub
       try {
           wspk = wychylenie;
           } catch (Exception e)
           {
            // TODO Auto-generated catch block
            e.printStackTrace();
           }
      }};
  
      // sending steering data
      public void Wyslij()
      {
          Socket socket = null;
           DataOutputStream dataOutputStream = null;
           DataInputStream dataInputStream = null;
           try {
               numer = adres.getText().toString();
               socket = new Socket(numer, 8888);
               dataOutputStream = new DataOutputStream(socket.getOutputStream());
               dataInputStream = new DataInputStream(socket.getInputStream());
               dataOutputStream.writeUTF(textOut.getText().toString());
                if(socket.isClosed())
                {
                    test.setText("Socket zamkniety");
                }
            //textIn.setText(dataInputStream.readUTF());
           } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           }
           finally{
                if (socket != null){
                 try {
                  socket.close();
                 } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                 }
                }
  
                if (dataOutputStream != null){
                 try {
                  dataOutputStream.close();
                 } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                 }
                }
  
                if (dataInputStream != null){
                 try {
                  dataInputStream.close();
                 } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                 }
                }
               }
  
      }
  
      //sending throttle data
      public void Gaz()
      {
          Socket socket = null;
           DataOutputStream dataOutputStream = null;
           DataInputStream dataInputStream = null;
           try {
               numer = adres.getText().toString();
               socket = new Socket(numer, 8889);
               dataOutputStream = new DataOutputStream(socket.getOutputStream());
               dataInputStream = new DataInputStream(socket.getInputStream());
               dataOutputStream.writeUTF(gazuje.getText().toString());
                if(socket.isClosed())
                {
                    test.setText("Socket zamkniety");
                }
            //textIn.setText(dataInputStream.readUTF());
           } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           }
           finally{
                if (socket != null){
                 try {
                  socket.close();
                 } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                 }
                }
  
                if (dataOutputStream != null){
                 try {
                  dataOutputStream.close();
                 } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                 }
                }
  
                if (dataInputStream != null){
                 try {
                  dataInputStream.close();
                 } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                 }
                }
               }
  
      }
  
  }
  </code></pre>
  
  <p>And here's Server code:</p>
  
  <pre><code>//import's...
  
  
  public class Okno 
  {
      public static float wychylenie;
      public static String gaz="0";
      public static float jedzie;
      public static int skrecam, gazuje;
      public static String wiadomosc="100";
      private static int maxConnections=0, port=8888, portg=8889;
      public static void main(String[] args)
      {
          skrecam = 0;
          gazuje = 0;
          Window ok = new Window();
          ok.setDefaultCloseOperation(3);
          ok.setVisible(true);
          ok.setResizable(false);
          ok.setTitle("Serwer TCP");
  
          int i=0;
  
          try{
              Robot robot = new Robot();
              Robot robotgaz = new Robot();
              ServerSocket listener = new ServerSocket(port);
              ServerSocket listenergaz = new ServerSocket(portg);
  
            while((i++ &lt; maxConnections) || (maxConnections == 0)){
  
             //create thread for steering
              if(skrecam == 0)
              {
                  skrecam=1;
              doComms conn_c= new doComms(listener);
              Thread t = new Thread(conn_c);
              t.start();
              }
  
              //create thread for throttle
              if(gazuje == 0)
              {
                  gazuje=1;
              doCommsgaz conn_gaz= new doCommsgaz(listenergaz);
              Thread tgaz = new Thread(conn_gaz);
              tgaz.start();
              }
  
              ok.pole3.setText(wiadomosc);
              ok.pole2.setText(gaz);
  
            }
          } 
          catch (AWTException e) {
              e.printStackTrace();
          }
          catch (IOException ioe) {
              //System.out.println("IOException on socket listen: " + ioe);
              ioe.printStackTrace();
            }
  
      }
  
  }
  
      class doComms implements Runnable {
          private Socket server;
          private ServerSocket listener;
          private String line,input;
  
          doComms(ServerSocket listener) {
              this.listener=listener;
            }
  
          public void run () {
  
            input="";
  
            try {
  
                Socket server;
                server = listener.accept();
              // Get input from the client
              DataInputStream in = new DataInputStream (server.getInputStream());
              //PrintStream out = new PrintStream(server.getOutputStream());
  
              Okno.wiadomosc = in.readUTF();
  
              server.close();
              Okno.skrecam=0;
            } catch (IOException ioe) {
              //System.out.println("IOException on socket listen: " + ioe);
              ioe.printStackTrace();
            }
          }
      }
  
      class doCommsgaz implements Runnable {
          private Socket server;
          private ServerSocket listener;
          private String line,input;
  
          doCommsgaz(ServerSocket listener) {
              this.listener=listener;
            }
  
          public void run () {
  
            input="";
  
            try {
  
                Socket server;
                server = listener.accept();
              // Get input from the client
              DataInputStream in = new DataInputStream (server.getInputStream());
              //PrintStream out = new PrintStream(server.getOutputStream());
  
              Okno.gaz = in.readUTF();
  
              server.close();
              Okno.gazuje=0;
            } catch (IOException ioe) {
              //System.out.println("IOException on socket listen: " + ioe);
              ioe.printStackTrace();
            }
          }
      }
  
  class Window extends JFrame {
      private JButton ustaw;
      public JTextField pole1;
      public JTextField pole2;
      public JTextField pole3;
      Window()
      {
          setSize(300,200);
          getContentPane().setLayout(new GridLayout(4,1)); 
          JPanel panel1 = new JPanel();
          panel1.setLayout(new FlowLayout(1));
          getContentPane().add(panel1);
          pole1 = new JTextField(15);
          panel1.add(pole1);
          JPanel panel2 = new JPanel();
          panel2.setLayout(new FlowLayout(1));
          getContentPane().add(panel2);
          pole2 = new JTextField(15);
          panel2.add(pole2);
          JPanel panel3 = new JPanel();
          panel3.setLayout(new FlowLayout(1));
          getContentPane().add(panel3);
          pole3 = new JTextField(15);
          panel3.add(pole3);
          JPanel panel4 = new JPanel();
          panel4.setLayout(new FlowLayout(1));
          getContentPane().add(panel4);
          ustaw = new JButton("Ustaw");
          panel4.add(ustaw);
          //action button handler
          ustaw.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent zdarz){
              try{
              }
              catch(Exception wyjatek){}
              pole1.setText("costam");
          }
      });
      }
  }
  </code></pre>
  
  <p>Once again, sorry for the non optimized, and hard-to-read code. But please, if someone knows what would be better, please respond.</p>
  
  <p>Thanks a lot!</p>