zoukankan      html  css  js  c++  java
  • 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;
    }
    }
    }

  • 相关阅读:
    网页色彩搭配
    jquery富文本在线编辑器UEditor
    编写、部署、应用JavaBean
    图片存储构架学习
    JVM内存管理(一)
    同步or异步
    分库分表策略的可实现架构
    百万数据查询优化技巧三十则
    匿名内部类
    MySQL limit分页查询优化写法
  • 原文地址:https://www.cnblogs.com/lvlv/p/3629616.html
Copyright © 2011-2022 走看看