JAVA UDP通信为什么只能接收一次数据,我想要时刻接收数据,并更新UI,大神们帮我看看程序吧?

// 与UDP数据接收线程通信更新UI线程中EditText控件中的内容
receiveHandler = new Handler() {
public void handleMessage(Message msg) {
point2.setText(receiveInfo);

        }
    };
}

// UDP数据接收线程
public class udpReceiveThread extends Thread {
@Override
public void run() {
try {
socket = new DatagramSocket(8081);
listenStatus = true;
while (listenStatus)
{
// byte[] inBuf= new byte[1024];
byte[] inBuf = new byte[1024];
DatagramPacket inPacket = new DatagramPacket(inBuf,
inBuf.length);
socket.receive(inPacket);
String str = new String(inPacket.getData());
receiveInfo = Change1(str, inPacket.getLength()).trim();

            //  receiveInfo = new String (inPacket.getData());  
                // receiveInfo= stringtopoint(inBuf,inPacket.getLength());
                socket.close();
                Message msg = new Message();
                receiveHandler.sendMessage(msg);
                try {Thread.sleep(100);

                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            // TODO Auto-generated catch block
        }
    }

}

// 发送按钮单击事件
public void SendButtonClick(View source) {
    new udpSendThread().start();
}

// 监听按钮点击事件
public void ListenButtonClick(View source) {
    if (listenStatus == false) {
        stop.setText("停止监听");
        new udpReceiveThread().start();
    } else {
        stop.setText("开始监听");
        socket.close();
        listenStatus = false;
        new udpReceiveThread().interrupt();
    }
}

// 数据处理

public static String Change1(String str, int len)
{

    if (str == null || str.equals("")) 
    {
        return null;
    }

    String hexString = str.replace(" ", "");
    String ret = "";
    char[] hexChars = hexString.toCharArray();
    for (int i = 0; i < hexChars.length; i++) 
    {

            if ((hexChars[i] == 'p') & (hexChars[i + 1] == '1')
                    & (hexChars[i + 2] == 'r') & (hexChars[i + 3] == '!')) 
            {
                String p = Integer
                        .toString((CharToHex(hexChars[i + 7]) << 12)
                                | (CharToHex(hexChars[i + 8]) << 8)
                                | (CharToHex(hexChars[i + 9]) << 4)
                                | CharToHex(hexChars[i + 10]));
                i=i+13;
                return p;
            } else 
            {   
                i=1+1;
            }
        }
    return null;

}

比如我发送了p1r!p1r003B1s!p1r!p1r001A1s!,程序只处理了p1r!p1r003B1s!这句话,把我需要的003B提取出来了,更新ui,为什么不能继续处理后面的数据,继续更新ui呢?请大神赐教!

1个回答

大神们快来看一下!是不是我的监听有问题呢,还是要把监听这个地方改一下!

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐