Оптимизация Java Socket Отправка Android на ПК - PullRequest
0 голосов
/ 28 мая 2011

Мне нужна ваша помощь!

Итак, я получил это приложение на устройстве Android, в котором я получаю данные от акселерометра и нажимаю кнопки, которые передают эти данные в текст редактирования и устанавливают слушателей на тексты редактирования..

Когда это изменилось, есть функция, которая создает сокет, отправляет данные и закрывает сокет.

Затем у меня на компьютере есть серверное приложение, в котором я создаю серверные сокеты и создаю два потока, ожидающих serversocket.accept(), которые получают данные и помещают их в texbox.Просто как тот.

Я рад, что у меня все равно получилось :-) но дело в том, что он работает не так хорошо.Я считаю, что все общение плохо и не оптимизировано.Он отправляет данные хорошо, но часто зависает, затем размораживает и быстро отправляет все предыдущие данные и так далее.

Прошу прощения за мой плохой код, но может кто-нибудь, пожалуйста, внимательно посмотреть на это и предложить, что мне следует изменить и как я мог бы сделать его более плавным и стабильным?: - (

Вот код клиента:

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();
               }
              }
             }

    }

}

А вот код сервера:

//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++ < 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");
        }
    });
    }
}

Еще раз, извините за неоптимизированный и трудный для-читать код. Но, пожалуйста, если кто-то знает, что было бы лучше, пожалуйста, ответьте.

Большое спасибо!

1 Ответ

0 голосов
/ 28 мая 2011

Код сокета клиента должен входить в AsyncTask . У Google есть все, что нужно здесь . Это ничего не ускорит, но остановит замораживание вашего приложения. Вы можете добавить сообщение «Обработка» во время отображения диалогового окна прогресса, чтобы пользователь знал, что что-то происходит.

...