區域網路下Android與scoket通訊的實現

來源:互聯網
上載者:User

標籤:adl   back   wrap   bubuko   java實現   分享   write   gravity   block   

因為最近實驗室項目要求實現在區域網路下將android app資料發送到winsock中進行儲存,所以對此進行了簡單學習。pc端因為是另一個同學做的,所以不做說明。

在android端,首先添加許可權:

    <uses-permission android:name="android.permission.INTERNET"/>  

 之後對app介面進行簡單設計——main.xml:

    <LinearLayout              android:orientation="horizontal"              android:layout_width="match_parent"              android:layout_height="wrap_content">              <!-- 定義一個文字框,它用於接收使用者的輸入 -->              <EditText                  android:id="@+id/input"                  android:layout_width="280dp"                  android:layout_height="wrap_content" android:inputType=""/>              <Button                  android:id="@+id/send"                  android:layout_width="match_parent"                  android:layout_height="wrap_content"                  android:paddingStart="8dp"                  android:text="@string/send"/>          </LinearLayout>          <!-- 定義一個文字框,它用於顯示來自伺服器的資訊 -->          <TextView              android:id="@+id/show"              android:layout_width="match_parent"              android:layout_height="match_parent"              android:gravity="top"              android:background="#ffff"              android:textSize="14sp"              android:textColor="#f000"/>  

 介面如下:

建立ClientThread.java用於實現區域網路下資料的傳輸:

public class ClientThread implements Runnable{private Socket s;// 定義向UI線程發送訊息的Handler對象private Handler handler;// 定義接收UI線程的訊息的Handler對象public Handler revHandler;// 該線程所處理的Socket所對應的輸入資料流BufferedReader br = null;OutputStream os = null;public ClientThread(Handler handler){this.handler = handler;}public void run(){try{s = new Socket("192.168.1.133", 8040);br = new BufferedReader(new InputStreamReader(s.getInputStream()));os = s.getOutputStream();// 啟動一條子線程來讀取伺服器響應的資料new Thread(){@Overridepublic void run(){String content = null;// 不斷讀取Socket輸入資料流中的內容try{while ((content = br.readLine()) != null){// 每當讀到來自伺服器的資料之後,發送訊息通知程式// 介面顯示該資料Message msg = new Message();msg.what = 0x123;msg.obj = content.toString();handler.sendMessage(msg);}}catch (IOException e){e.printStackTrace();}}}.start();// 為當前線程初始化LooperLooper.prepare();// 建立revHandler對象revHandler = new Handler(){@Overridepublic void handleMessage(Message msg){// 接收到UI線程中使用者輸入的資料if (msg.what == 0x345){// 將使用者在文字框內輸入的內容寫入網路try{os.write((msg.obj.toString() + "\r\n").getBytes("utf-8"));}catch (Exception e){e.printStackTrace();}}}};// 啟動LooperLooper.loop();}catch (SocketTimeoutException e1){System.out.println("網路連接逾時!!");}catch (Exception e){e.printStackTrace();}}}

 最後建立MainActivity.java實現app中發送內容的擷取等功能:

public class MainActivity extends Activity{// 定義介面上的兩個文字框EditText input;TextView show;// 定義介面上的一個按鈕Button send;Handler handler;// 定義與伺服器通訊的子線程ClientThread clientThread;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);input = (EditText) findViewById(R.id.input);send = (Button) findViewById(R.id.send);show = (TextView) findViewById(R.id.show);handler = new Handler() // ②{@Overridepublic void handleMessage(Message msg){// 如果訊息來自於子線程if (msg.what == 0x123){// 將讀取的內容追加顯示在文字框中show.append("\n" + msg.obj.toString());}}};clientThread = new ClientThread(handler);// 用戶端啟動ClientThread線程建立網路連接、讀取來自伺服器的資料new Thread(clientThread).start(); // ①send.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){try{// 當使用者按下發送按鈕後,將使用者輸入的資料封裝成Message// 然後發送給子線程的HandlerMessage msg = new Message();msg.what = 0x345;msg.obj = input.getText().toString();clientThread.revHandler.sendMessage(msg);// 清空input文字框input.setText("");}catch (Exception e){e.printStackTrace();}}});}}

 這樣,就實現了我們想要的傳輸資料到pc中的功能了。

區域網路下Android與scoket通訊的實現

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.