不幸的是,我无法通过UDP发送简单的字符串消息。代码很简单。我创建了一个SendLocation类,我希望用它发送一个位置消息。我每次尝试时都会得到"无法发送它"信息。任何的想法?非常感谢!
(messDelay,messCount,ip,port是EditTexts)
private class SendLocation extends Thread {
private String message = "";
private volatile boolean flag = true;
public SendLocation(String message) {
this.message = message;
}
@Override
public void run() {
while (flag) {
try {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Server.this, message, Toast.LENGTH_SHORT).show();
}
});
byte[] data = message.getBytes();
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName(ip.getText().toString()),
Integer.valueOf(port.getText().toString()));
for (int i = 0; i < Integer.valueOf(messCount.getText().toString()); i++) {
socket.send(packet);
Thread.sleep(Integer.valueOf(messDelay.getText().toString()));
}
socket.close();
} catch (Exception e) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Server.this, "Can't send it", Toast.LENGTH_SHORT).show();
}
});
}
flag = false;
}
}
}