2012-06-25 25 views
0

我有c + +套接字服務器和Android客戶端。服務器在一段時間間隔後不斷向客戶端發送數據。問題是如何實現這個獲取Android客戶端上的數據如何監視Android客戶端上的套接字服務器活動?

socket = new Socket("xxx.xxx.xxx.x", xxxx); // I connect 
.... socket.getInputStream();    // Get first input stream 

如何使它不斷接收數據?我試過這樣的事情(true){..socket.getInputStream();了Thread.sleep(...); }它沒有幫助

+0

這裏插座編程基礎知識的一個很好的例子爲Android看看這個鏈接,可以幫助ü HTTP ://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/ – Aamirkhan

回答

3

請注意,您只需打開一次輸入流。然後,如果您對輸入流執行read()操作,它將會阻塞(當然,如果使用阻塞讀取(blocking vs non-blocking read))。

你可以找到關於Java Socket編程此信息:link

你可以找到丟失的例子爲socket編程Android平臺上的位置:link

例如:

BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
String line = ""; 
while (true) { 
    line = br.readLine(); // at this line, execution will stop until data is received 
    System.out.println("The read line is: " + line); 
} 
br.close(); 
+0

我明白如何使用套接字,如何連接,發送和接收形成。問題是如何實現客戶端連續監聽服務器並顯示收到的信息 –

+0

好了,讓我直接說明:打開套接字流並執行'read()'。執行'read()'的線程將阻塞並且不執行任何操作,直到您向其發送數據爲止。當在數據流中接收到數據時,線程會「喚醒」,並且您可以處理接收到的數據(例如,您可以將其放在屏幕上)。我添加了一些編輯的答案。 – overbet13

+0

生成服務器的數據是一個圖像,我通過這段代碼得到它* Bitmap bmp = BitmapFactory.decodeStream(socket.getInputStream())*;如何在服務器發送後獲取此映像?對不起,沒有正確的解釋。 –

0

你可以使用此Webstart Application並創建一個本地服務器,通過提供您的IP地址和端口 ,並可以在下面的代碼中使用相同的IP地址和端口作爲客戶... ...!你可以發送和接收消息。並且在AndroidManifest中提供INTERNET權限。

MainActivity.java

import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.InetSocketAddress; 
import java.net.Socket; 
import java.net.SocketAddress; 

import android.app.Activity; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.Environment; 
import android.util.Base64; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ImageView; 
import android.widget.TextView; 

public class MainActivity extends Activity { 
    Button btnStart, btnSend, disconnect; 
    TextView textStatus; 
    EditText message, ipAddress, port; 
    ImageView image; 
    NetworkTask networktask; 
    String ip, prt; 
    Socket nsocket; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     btnStart = (Button)findViewById(R.id.btnStart); 
     disconnect = (Button)findViewById(R.id.bDisconnect); 
     btnSend = (Button)findViewById(R.id.btnSend); 
     textStatus = (TextView)findViewById(R.id.textStatus); 
     image = (ImageView)findViewById(R.id.ivBit); 
     message = (EditText) findViewById(R.id.message); 
     ipAddress = (EditText)findViewById(R.id.ipAddress); 
     port = (EditText)findViewById(R.id.port); 
     btnStart.setOnClickListener(btnStartListener); 
     btnSend.setOnClickListener(btnSendListener); 
     disconnect.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       try { 
        nsocket.close(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

      } 
     }); 

//  networktask = new NetworkTask(ip, prt); //Create initial instance so SendDataToNetwork doesn't throw an error. 
    } 

    private OnClickListener btnStartListener = new OnClickListener() { 
     public void onClick(View v){ 
      disconnect.setVisibility(View.VISIBLE); 
      btnStart.setVisibility(View.GONE); 
      ipAddress.setEnabled(false); 
      port.setEnabled(false); 
      ip = ipAddress.getText().toString(); 
      prt = port.getText().toString(); 
      System.out.println("IPADDRESS :::::::" + ip); 
      System.out.println("PORT :::::::" + prt); 
      networktask = new NetworkTask(ip, prt); //New instance of NetworkTask 
      networktask.execute(); 
     } 
    }; 
    private OnClickListener btnSendListener = new OnClickListener() { 
     public void onClick(View v){ 
      textStatus.setText("Sending Message to AsyncTask."); 
      networktask.SendDataToNetwork(message.getText().toString() + "\n"); 

     } 
    }; 


    public class NetworkTask extends AsyncTask<Void, byte[], Boolean> { 
     //Network Socket 
     InputStream nis; //Network Input Stream 
     OutputStream nos; //Network Output Stream 
     String data = ""; //Data Received 
     String ip, prt; 

     public NetworkTask(String ip, String prt) { 
      // TODO Auto-generated constructor stub 
      this.ip = ip; 
      this.prt = prt; 
     } 

     @Override 
     protected void onPreExecute() { 
      Log.i("AsyncTask", "onPreExecute"); 
     } 

     @Override 
     protected Boolean doInBackground(Void... params) { //This runs on a different thread 
      boolean result = false; 
      try { 
       Log.i("AsyncTask", "doInBackground: Creating socket"); 
       SocketAddress sockaddr = new InetSocketAddress(ip, Integer.parseInt(prt)); //192.168.2.102 118.139.161.101 
       nsocket = new Socket(); 
       nsocket.connect(sockaddr, 500); //10 second connection timeout 
       if (nsocket.isConnected()) { 

        nis = nsocket.getInputStream(); 
        nos = nsocket.getOutputStream(); 
        Log.i("AsyncTask", "doInBackground: Socket created, streams assigned"); 
        Log.i("AsyncTask", "doInBackground: Waiting for inital data..."); 
        byte[] buffer = new byte[4096]; 
        int read = nis.read(buffer, 0, 4096); //This is blocking 
        while(read != -1){ 
         byte[] tempdata = new byte[read]; 
         System.arraycopy(buffer, 0, tempdata, 0, read); 
         publishProgress(tempdata); 
         Log.i("AsyncTask", "doInBackground: Got some data"); 
         read = nis.read(buffer, 0, 4096); //This is blocking 
        } 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
       Log.i("AsyncTask", "doInBackground: IOException"); 
       result = true; 
      } catch (Exception e) { 
       e.printStackTrace(); 
       Log.i("AsyncTask", "doInBackground: Exception"); 
       result = true; 
      } finally { 
       try { 
        nis.close(); 
        nos.close(); 
        nsocket.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
       Log.i("AsyncTask", "doInBackground: Finished"); 
      } 
      return result; 
     } 

     public void SendDataToNetwork(String cmd) { //You run this from the main thread. 
      try { 
       if (nsocket.isConnected()) { 
        Log.i("AsyncTask", "SendDataToNetwork: Writing received message to socket"); 
        nos.write(cmd.getBytes()); 
       } else { 
        Log.i("AsyncTask", "SendDataToNetwork: Cannot send message. Socket is closed"); 
       } 
      } catch (Exception e) { 
       Log.i("AsyncTask", "SendDataToNetwork: Message send failed. Caught an exception"); 
      } 
     } 



     @Override 
     protected void onProgressUpdate(byte[]... values) { 
      if (values.length > 0) { 
       Log.i("AsyncTask", "onProgressUpdate: " + values[0].length + " bytes received."); 

       data += new String(values[0]); 
       textStatus.setText(data); 
       System.out.println("DATA RECEIVED..........." + (data)); 
      } 
     } 
     @Override 
     protected void onCancelled() { 
      Log.i("AsyncTask", "Cancelled."); 
      disconnect.setVisibility(View.VISIBLE); 
      btnStart.setVisibility(View.GONE); 
      ipAddress.setEnabled(true); 
      port.setEnabled(true); 
     } 
     @Override 
     protected void onPostExecute(Boolean result) { 
      if (result) { 
       Log.i("AsyncTask", "onPostExecute: Completed with an Error."); 
       textStatus.setText("There was a connection error."); 
      } else { 
       Log.i("AsyncTask", "onPostExecute: Completed."); 
      } 
      disconnect.setVisibility(View.GONE); 
      btnStart.setVisibility(View.VISIBLE); 
      ipAddress.setEnabled(true); 
      port.setEnabled(true); 
     } 
    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     networktask.cancel(true); //In case the task is currently running 
    } 
} 

main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <EditText 
     android:id="@+id/ipAddress" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:digits="." 
     android:inputType="number" /> 

    <EditText 
     android:id="@+id/port" 
     android:layout_width="100dp" 
     android:layout_height="wrap_content" 
     android:digits="." 
     android:inputType="number" /> 

    <Button 
     android:id="@+id/bDisconnect" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:visibility="gone" 
     android:text="Disconnect" /> 

    <Button 
     android:id="@+id/btnStart" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Start AsyncTask" > 
    </Button> 

    <EditText 
     android:id="@+id/message" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:ems="10" 
     android:inputType="textMultiLine" > 

    </EditText> 

    <Button 
     android:id="@+id/btnSend" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Send Message" > 
    </Button> 

    <ScrollView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" > 

     <LinearLayout 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" > 

      <TextView 
       android:id="@+id/textStatus" 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:text="Status Goes Here" 
       android:textSize="24sp" /> 

      <ImageView 
       android:id="@+id/ivBit" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" /> 
     </LinearLayout> 
    </ScrollView> 

</LinearLayout> 
相關問題