android之TCP客戶端框架


一、程序框架

  1.1 創建方法

    onCreate

      1.1.1 創建連接按鍵線程,並使能線程(觸發原因:可按鍵、其他操作,並進行狀態判斷):

        Connect_Thread connect_Thread = new Connect_Thread();

        connect_Thread.start();

      1.1.2 關閉連接按鍵線程,並復位(觸發原因:可按鍵、其他操作,並進行狀態判斷):

        socket.close();

        socket=null;

      1.1.3 發送給服務器數據(觸發原因:可按鍵、其他操作):

        outputStream = socket.getOutputStream();

        outputStream.write(MsgEditText.getText().toString().getBytes());

  1.2 連接線程

    class Connect_Thread extends Thread

    1.2.1 run方法

      1.2.1.1 如果socket為null,即沒連接過

          InetAddress ipAddress = InetAddress.getByName(IPEditText.getText().toString());//這里獲取IP是通過EditText,也可以其他賦值給InetAddress

          int port =Integer.valueOf(PortText.getText().toString());//這里獲取端口號是通過EditText,也可以其他賦值給InetAddress

          socket = new Socket(ipAddress, port);//創建連接地址和端口

      1.2.1.2 在創建完連接后啟動接收線程

            Receive_Thread receive_Thread = new Receive_Thread();

            receive_Thread.start();

  1.3 讀取線程

    class Receive_Thread extends Thread

    1.3.1 run方法

      死循環一直讀取

      final byte[] buffer = new byte[1024];//創建接收緩沖區

       inputStream = socket.getInputStream();

      final int len = inputStream.read(buffer);//數據讀出來,並且返回數據的長度

      runOnUiThread(new Runnable() {

        @Override

        public void run() {

        RrceiveEditText.setText(new String(buffer,0,len));

          }
      });

效果圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM