• android DatagramSocket send 发送数据出错


    安卓4.0以后好像不能在主线程里面使用 socket 所以不管是发送数据还是接收数据需要新开一个了线程:

    以下代码是我点击发送是代码:

    new Thread(new Runnable() {
    @Override
    public void run() {

    try {
      sendData();
    } catch (Exception e) {
      Log.e(_TAG, "Check: Error2: " + e);
    } finally {

    }
    }
    }).start();

    private void sendData()
    {

    DatagramSocket socket=null;
    try {
    socket = new DatagramSocket();
    } catch (SocketException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    InetAddress serverAddress=null;
    try {
    serverAddress = InetAddress.getByName("192.168.1.101");
    } catch (UnknownHostException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    String str = "hello";
    byte data[] = str.getBytes();
    DatagramPacket pkdata = new DatagramPacket (data , data.length , serverAddress , 8899);
    try {

    socket.send(pkdata);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    Log.v(null,e.getMessage()+"11111111111");
    e.printStackTrace();
    }
    finally {
    if (null != socket) {
    socket.close();
    socket = null;
    }
    }
    }

  • 相关阅读:
    使用Mint-UI的Loadmore实现上拉加载更多和下拉刷新
    JavaScript的日常所得
    web网站性能优化整理
    ArrayBuffer
    Blob
    FormData
    FileReader
    websocket的实践
    Vue CLI 3的Vue.config.js
    css行高line-height的一些深入理解及应用
  • 原文地址:https://www.cnblogs.com/lvlv/p/3629616.html
Copyright © 2020-2023  润新知