优化Java套接字将Android发送到PC

时间:2011-05-28 12:42:04

标签: java android sockets optimization

我需要你的帮助!

所以我在Android设备上安装了这个应用程序,我从加速度计中获取数据,然后按下按钮将这些数据转换为edittext,并在edittextes上设置监听器。

当它被改变时,有一个函数可以创建套接字,发送数据和关闭套接字。

然后我在我的计算机上有一个服务器应用程序,我在其中创建服务器套接字,并创建两个等待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 :(得分:0)

客户端套接字代码应该进入AsyncTask。 Google对此有很好的了解here。这不会加速任何事情,但它会阻止你的应用程序冻结。您可以在显示进度对话框时输入“正在处理”消息,以便让用户知道正在发生的事情。