qq_35383077 2016-06-21 19:50 采纳率: 75%
浏览 3585
已采纳

为什么我android UDP通信 只能发信息接收不到信息。请大神帮忙

主进程

import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class YuntuActivity extends ActionBarActivity implements OnClickListener {

private TextView adSpeed;
private TextView reSpeed;
private TextView reTxt;
private Button btnHeadCar;
private Button btnAgree;
private Button btnApply;
private Button btnStart;
private Button btnExit;

//自定义变量
private String remoteIP = null;
private int rePort = 0;
private int loPort = 0;
private UDPThread reTxtThread = null;
private UDPThread adSpeedThread = null;
private UDPThread reSpeedThread = null;
private String sendStr = null;//发送的字符串
private String receStr = null;


Handler mhander = new Handler() {

    public void handleMessage(Message msg) {

        Bundle bundle =new Bundle();
        bundle = msg.getData();
        receStr = bundle.getString("info");
        reTxt.setText(receStr);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_yuntu);

    //初始化UI
    initUI();

    //初始化
    init();

    reTxtThread = new UDPThread(mhander);

}

private void init() {
    remoteIP = "172.22.130.124";
    rePort = 8801;
    loPort = 8805;
}

//初始化UI
private void initUI() {
    adSpeed =(TextView)findViewById(R.id.AdSpeed);
    reSpeed =(TextView)findViewById(R.id.ReSpeed);
    reTxt =(TextView)findViewById(R.id.reTxt);
    btnHeadCar =(Button)findViewById(R.id.button1);
    btnAgree =(Button)findViewById(R.id.button2);
    btnApply =(Button)findViewById(R.id.button3);
    btnStart =(Button)findViewById(R.id.button4);
    btnExit =(Button)findViewById(R.id.button5);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    //点击  同意入队  按钮
    case R.id.button1:
        sendStr = "you can join in flownteam.";
        if(!sendStr.trim().equals("")) {
            reTxtThread.sendData(sendStr);
        }
        break;  

        //点击 申请入队按钮
    case R.id.button2:
        sendStr = "Can I join in?";
        if(!sendStr.trim().equals("")) {
            reTxtThread.sendData(sendStr);
        }
        break;  

        //点击申请离队按钮
    case R.id.button3:
        sendStr = "Can I exit?";
        if(!sendStr.trim().equals("")) {
            reTxtThread.sendData(sendStr);
        }
        break;  

        //点击开始监听按钮
    case R.id.button4:
        reTxtThread.setReomteIP(remoteIP);

        reTxtThread.setRePort(rePort);

        reTxtThread.setLoPort(loPort);

        boolean connResult = reTxtThread.connectSocket();

        if(connResult) {
            Toast.makeText(getApplicationContext(), "链接建立完毕!", Toast.LENGTH_SHORT).show();
        }

        break;          

        //点击关闭监听按钮  
    case R.id.button5:
            reTxtThread.disConnectSocket();
            Toast.makeText(getApplicationContext(), "链接已经关闭!", Toast.LENGTH_SHORT).show();

        break;
    default:
        break;
    }
}

}

子线程:接收和发送UDP包
package com.example.cqput_yuntu2;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.TextView;

public class UDPThread implements Runnable {

// 定义变量
private TextView rTextView = null;
private String reomteIP = null;
private int rePort = 0;
private int loPort = 0;
private Thread rThread = null;
private static String CHARECTER = "UTF-8";
private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

// 接收
private byte[] rBuffer = new byte[1024];
private DatagramSocket rSocket = null;
private DatagramPacket rPacket = null;
private String rStr = null;

// 发送
private DatagramSocket sSocket = null;
private DatagramPacket sPacket = null;
private byte[] sBuffer = new byte[1024];
public Handler mhandler;

public UDPThread(Handler handler) {
    mhandler = handler;
}

@Override
public void run() {
    // 开始接收数据
    Looper.prepare();
    if (Thread.currentThread() == rThread) {
        System.out.println("------jieshouqian");
        rStr = receiveData();
        System.out.println("------jieshouhou");
        Message toMain = mhandler.obtainMessage();

        Bundle bundle = new Bundle();
        bundle.putString("info", rStr);
        toMain.setData(bundle);
        mhandler.sendMessage(toMain);

    }
    ;
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

// 开始接收数据
private String receiveData() {
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(rBuffer);
        DataInputStream dis = new DataInputStream(bais);
        if (rSocket == null) {
            rSocket = new DatagramSocket(8805);
        }
        if (rPacket == null) {
            rPacket = new DatagramPacket(rBuffer, rBuffer.length);
        }
        System.out.println("----rece");
        rSocket.receive(rPacket);
        System.out.println("------receHou");
        rStr = dis.readUTF().trim();
        System.out.println("------jieBeg");
        rStr = String.format("[%s:%d//%s]%s", rPacket.getAddress()
                .getHostAddress(), rPacket.getPort(), sdf
                .format(new Date()), rStr);

        return rStr;
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("-----------------recvdata error:"
                + e.getMessage());
    }
    return null;
}

// 建立连接
public boolean connectSocket() {
    boolean result = false;

    // 开启一个新的线程
    startThread();
    System.out.print("监听线程开启");
    result = true;

    return result;
}

// 关闭连接
public void disConnectSocket() {
    if (rSocket != null) {
        rSocket.close();
        rSocket = null;
    }

    if (rPacket != null) {
        rPacket = null;
    }

    // 关闭线程
    stopThread();
}

// 关闭线程
private void stopThread() {
    if (rThread != null) {
        rThread.stop();
        rThread = null;
    }
}

// 开启新的线程
private void startThread() {
    if (rThread == null) {
        rThread = new Thread(this);
        rThread.start();
    }
}

// 开始发送数据
public void sendData(String sendStr) {

    try {
        // 包装数据
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeUTF(sendStr);
        sBuffer = baos.toByteArray();
        if (sSocket == null) {
            sSocket = new DatagramSocket();
        }
        if (sPacket == null) {
            sPacket = new DatagramPacket(sBuffer, sBuffer.length,
                    InetAddress.getByName(reomteIP), rePort);
        }
        sSocket.send(sPacket);
        sSocket.close();
        sSocket = null;
        sPacket = null;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        sSocket.close();
        sSocket = null;
        sPacket = null;
        System.out.println("senddata error:" + e.getMessage());
    }
}

public void setReomteIP(String reomteIP) {
    this.reomteIP = reomteIP;
}

public void setRePort(int rePort) {
    this.rePort = rePort;
}

public void setLoPort(int loPort) {
    // this.loPort = loPort;
}

}

展开全部

  • 写回答

2条回答 默认 最新

  • wenbodong 2016-06-23 08:23
    关注

    remoteIP = "172.22.130.124";
    rePort = 8801;
    loPort = 8805;
    这IP应该是Internet上的某个主机吧,若手机与其不在同一局域网中(无论是3、4G还是连接热点,都要至少经过一层网关才能接入Internet,而网关一般都会对局域网内设备有保护。
    这里你开启的8801监听,默认情况下只有局域网内设备能访问它。除非你使用该端口向Internet上的主机发送消息,网关在将该消息转发出WAN口时,会为你临时打开一个端口映射,此时该消息的目标主机才可以在外网访问你开的这8801端口。更详细的原理,可以搜索“NAT穿透”。
    简言之,在局域网中使用UDP与外网主机双向通信,需要使用同一个端口进行收发,且得先使用该端口向外网主机的某端口发消息,才能收到该主机相应端口发的消息。
    另外,代码中收到数据包时解析也有问题,rStr = dis.readUTF().trim();收到的数据包大小是不固定的,而这里直接使用之前建立的输入流,读取整个rBuffer的数据,是不应该的。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 前端js怎么实现word的.doc后缀文件在线预览
  • ¥20 macmin m 4连接iPad
  • ¥15 DBIF_REPO_SQL_ERROR
  • ¥15 根据历年月数据,用Stata预测未来六个月汇率
  • ¥15 DevEco studio开发工具 真机联调找不到手机设备
  • ¥15 请教前后端分离的问题
  • ¥100 冷钱包突然失效,急寻解决方案
  • ¥15 下载honeyd时报错 configure: error: you need to instal a more recent version of libdnet
  • ¥15 距离软磁铁一定距离的磁感应强度大小怎么求
  • ¥15 霍尔传感器hmc5883l的xyz轴输出和该点的磁感应强度大小的关系是什么
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部