请大神帮我看看androi代码,UDP通信是能发,不能收,程序一直卡在收包那个点。怎么解决? 20C

主进程:

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

}

1个回答

你怎么确定能发?UDP发送是不阻塞的,任何情况下都会发出去。没有收到数据,你可以在程序中加入打印语句。看程序执行到哪?你要明确必须先有接受再发送才可以收到

qq_35383077
qq_35383077 回复hqyj15121: 谢谢,我之前是按照您说的方法操作的,server能收到包,但是就是返回消息时,client端收不到包。
接近 4 年之前 回复
hqyj15121
hqyj15121 回复qq_35383077:我的意思是server端必须先阻塞在接受出,客户端再发送
接近 4 年之前 回复
qq_35383077
qq_35383077 我自己用java写了个server端的小程序,该小程序逻辑是先接受client端的包 再返还一个包回来,我用了打印语句,打印语句一直卡在子线程receiveData方法中的rSocket.receive(rPacket);这里。还有您说的,必须先接收再发送是指client端必须先收到server端的信息才能发送数据过去吗?
接近 4 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问