Android之udp傳輸

來源:互聯網
上載者:User

標籤:

注意除了添加Internet許可權外,還要添加兩行代碼

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;import java.net.UnknownHostException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.UUID;import android.annotation.SuppressLint;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.os.StrictMode;import android.util.Log;@SuppressLint("NewApi") public class SocketUdp {    Thread mReceiveThread;      DatagramSocket serverReceive;     DatagramSocket serverSend;    InetAddress local = null;    //構造方法    public SocketUdp(){        try {              StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());                       if(serverReceive!=null){                serverReceive.close();                serverReceive=null;            }            serverReceive=new DatagramSocket(null);            serverReceive.setReuseAddress(true);            serverReceive.setBroadcast(true);            serverReceive=new DatagramSocket(5061);            mReceiveThread= new Thread(updateThread);              mReceiveThread.start();                                     local = InetAddress.getByName("192.168.1.51");            //server.setReuseAddress(true);          } catch (Exception e) {              e.printStackTrace();          }              }    // 接收資料處理    final Handler updateBarHandler = new Handler() {          @Override          public void handleMessage(Message msg) {              SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");//設定日期格式            String strDate=df.format(new Date());            String  receiveString =(msg.getData()).getString("data");            SysLogActivity.AddToLog(strDate+"  "+receiveString);            Log.e("接收:"+strDate,receiveString);                          // 接收資料處理                   }      };        // 線程類,該類使用匿名內部類的方式進行聲明      Runnable updateThread = new Runnable() {            public void run() {              try{                // 得到一個訊息對象,Message類是android系統提供的                  Message msg = new Message();                  Bundle b = new Bundle();              // 定義緩衝區                  byte[] buffer = new byte[1024];                  // 定義接收資料包                  DatagramPacket packet = new DatagramPacket(buffer,                          buffer.length);                  while (true) {                      msg = updateBarHandler.obtainMessage();                      // 接收資料                      serverReceive.receive(packet);                      // 判斷是否收到資料,然後輸出字串                      if (packet.getLength() > 0) {                          String str = new String(buffer, 0, packet                                  .getLength());                          b.putString("data", str + "\n");                          msg.setData(b);                          // 將Message對象加入到訊息佇列當中                          updateBarHandler.sendMessage(msg);                      }                  }              }            catch(Exception ex){                Log.e("socketUdp",ex.toString());              }        }      };        public void SendBuffer(byte[] buffer){        try {            serverSend =new DatagramSocket();            DatagramPacket p = new DatagramPacket(buffer, buffer.length, local,5060);            serverSend.send(p);            serverSend.close();                    } catch (IOException e) {            e.printStackTrace();        }    }        public void CloseMe(){        serverReceive.close();    }}
SocketUdp

 

Android之udp傳輸

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.