2011-05-28 106 views
0

我需要你的幫助!優化Java Socket發送Android到PC

因此,我在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"); 
     } 
    }); 
    } 
} 

再次,比較遺憾的是不優化,難以閱讀的代碼,但請,如果有人知道什麼會更好,請回復。

非常感謝!

回答

0

cl客戶端代碼應該進入AsyncTask。谷歌已經很好的瞭解了它here。這不會加速任何事情,但它會阻止你的應用程序凍結。您可以在顯示進度對話框的同時輸入「處理」消息,以讓用戶知道發生了什麼情況。

+0

感謝您的關注!當然我會檢查並使用AsyncTask,因爲它看起來很有用。但是,它真的能解決我的問題嗎?我的意思是,沒有火箭科學 - 我有很少的數據,需要發送它,我希望它實時發送,沒有堵塞,但我的技能,我不能。 – Boro 2011-05-28 18:04:03