溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

android socket通信 創(chuàng)建線程接受 客戶端

發(fā)布時(shí)間:2020-07-26 14:31:03 來源:網(wǎng)絡(luò) 閱讀:611 作者:天天12321 欄目:移動(dòng)開發(fā)

//聲明量

   private String      IPaddress="192.168.1.120";

   private int         port =50003;

   private Handler mhandler =null;

   private String cc ="";

   private  TextView returnvalue;



//  動(dòng)態(tài)接收數(shù)據(jù)

mhandler = new Handler(){

       public voidhandleMessage(Message msg)

       {

         if(msg.what== 1)

         {

            if(cc!=null||cc!="")

            {

              returnvalue.setText(cc);

              cc=null;

            }


         }

         super.handleMessage(msg);

       }

    };

//啟動(dòng)相關(guān)線程

    serverThread thread = new serverThread();

    thread.start();

// 創(chuàng)建并發(fā)送數(shù)據(jù)

  byte[] buf =  {(byte)0x55,(byte)0xAA};

       try {


       socket = newSocket(this.IPaddress,this.port);

         OutputStream out =socket.getOutputStream();

         OutputStreamWriter writer =new OutputStreamWriter(out);

         out.write(buf);

         writer.flush();

         Toast.makeText(PauseActivity.this,"成功",

              Toast.LENGTH_SHORT).show();

       } catch (UnknownHostExceptione) {

Toast.makeText(PauseActivity.this, "異常",

              Toast.LENGTH_SHORT).show();

         e.printStackTrace();

       } catch (IOException e) {

         e.printStackTrace();

       }



// 接受數(shù)據(jù)

  public class serverThread extendsThread  {

    publicvoid run() {

       while(!Thread.currentThread().isInterrupted()){

            if(socket==null)

            {

              try {

                 Thread.sleep(1000);

              } catch(InterruptedException e) {

                 // TODOAuto-generated catch block

                 e.printStackTrace();

              }

            }else

            {

                 try {

                   Thread.sleep(1000);

                   InputStreamips=socket.getInputStream();

                   InputStreamReader  in = new InputStreamReader(ips);

                   in.ready();

                   cc ="";

                   for(inti= 0 ;i<2 ;i++)

                   {

                      cc+=ips.read()+"-";

                   }


                 } catch(InterruptedException e) {

                   e.printStackTrace();

                 } catch(IOException e) {

                   e.printStackTrace();

                 }

                 Message msg = newMessage();

                  msg.what= 1;

                  mhandler.sendMessage(msg);

            }

       }

    }


   }


// 新人求關(guān)注


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI