2016-04-07 43 views
0

對於android來說我是新手,並且我在socket編程中遇到了一個問題。在Java中使用Socket編程來發送和接收字節數組

class ClientAsycTask extends AsyncTask<String,Void,String>{ 
    ProgressDialog progress; 
    @Override 
    protected void onPreExecute() { 
     progress = new ProgressDialog(MainActivity.this); 
     progress.setMessage("Connection Server Please wait"); 
     progress.setIndeterminate(true); 
     progress.show(); 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     String result = null; 
     Socket socket = new Socket(); 
     String host = "systemteq.gotdns.com"; 
     Integer port = 4999; 
     DataOutputStream s_out = null; 
     BufferedReader s_in = null; 
     try{ 
      socket.connect(new InetSocketAddress(host, port)); 
      s_out = new DataOutputStream(socket.getOutputStream()); 
      s_in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
      byte[] messages = new byte[]{0x10,0x01,0x03,0x00,0x00}; 
      s_out.write(messages); 
      String response; 
      while((response = s_in.readLine())!=null){ 
       result += response; 
      } 
      //result = "Successfully"+s_in.read();//s_in.readLine(); 
      socket.close(); 

     }catch (Exception e){ 
      Toast.makeText(MainActivity.this,"systemteq.gotdns.com:4999 not connected",Toast.LENGTH_SHORT).show(); 
     } 
     return result; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     if(progress.isShowing()){ 
      progress.dismiss(); 
     } 
     Toast.makeText(MainActivity.this,"Connected "+s,Toast.LENGTH_SHORT).show(); 
     tv.setText(s); 
    } 
} 

以上代碼發送一個十六進制碼到服務器以及從服務器與一些十六進制代碼做出響應,讓說10 01 20 10 00 [五字節]。

但是,當我運行上面的代碼進度對話框永遠不會關閉。在解決問題後,我發現s_in.readLine()在從服務器讀取響應時遇到了一些問題。

我已經經歷了很多鏈接,但是我在解決這個問題的時候並沒有成功。請幫我解決這個問題。

更新: -

使用DataInputStream類後: -

s_in = new DataInputStream(socket.getInputStream()); 
      byte[] messages = new byte[]{0x10,0x01,0x03,0x00,0x00}; 
      s_out.write(messages); 
      String response; 
      System.out.println("START"); 
      result = s_in.readUTF(); 

它仍然沒有采取應對字節。雖然請求是成功的。

更新2

byte m = s_in.readByte(); 
result = Byte.toString(m); 

現在越來越字節的值,但我應該得到5個字節,而不是讓5個字節我得到唯一的一個。請幫助我這個東西

回答

3

如果您正在等待二進制數據,請不要使用InputStreamReader,請嘗試使用DataInputStream
readLine()等待'\ n','\ r',「\ r \ n」或閱讀器的末尾。

更新:如果您知道確切的字節數,請將它們讀入數組中。

byte[] buf = new byte[5]; 
s_in.read(buf); 
+0

是的,我嘗試過。請檢查更新後的問題 – RKD

+0

我認爲readUTF的功能與readLine的功能相同 – RKD

+0

如果服務器向您發送字節,爲什麼您總是嘗試將它們讀爲String?將字節讀取到byte []緩衝區。這很容易。字符串更復雜。 –

相關問題