温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

android socket通信 创建线程接受 客户端

发布时间:2020-07-26 14:31:03 来源:网络 阅读:557 作者:天天12321 栏目:移动开发

//声明量

   private String      IPaddress="192.168.1.120";

   private int         port =50003;

   private Handler mhandler =null;

   private String cc ="";

   private  TextView returnvalue;



//  动态接收数据

mhandler = new Handler(){

       public voidhandleMessage(Message msg)

       {

         if(msg.what== 1)

         {

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

            {

              returnvalue.setText(cc);

              cc=null;

            }


         }

         super.handleMessage(msg);

       }

    };

//启动相关线程

    serverThread thread = new serverThread();

    thread.start();

// 创建并发送数据

  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();

       }



// 接受数据

  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);

            }

       }

    }


   }


// 新人求关注


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI