我正在尝试开发一个通过网络侦听udp广播数据包的示例应用程序,一旦收到广播,它就会用另一个数据包回复客户端。从服务器获取代表后,客户端发送一个单播消息到服务器没有收到。它工作正常,直到接收广播和回复,但接收单播消息不工作。我发布的代码。任何建议将非常感谢。
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class MyDatagramReceiver extends Thread {
private boolean bKeepRunning = true;
private String lastMessage = null;
private Handler mHandler = null;
private DatagramSocket datagramsocket = null;
DatagramPacket packet = null;
private static InetAddress Serverip = null;
private static int port = 8090;
public MyDatagramReceiver(Handler handler) {
this.mHandler = handler;
Log.v("MyDatagramReceiver", "Handler Initialised");
}
public void run() {
String message = null;
InetAddress ip = null;
byte[] lmessage = new byte[10];
try {
Serverip = getDeviceIP();
Log.v("MyDatagramReceiver", "DeviceIp:" + Serverip);
datagramsocket = new DatagramSocket(port, Serverip);
datagramsocket.setSoTimeout(5000);
datagramsocket.setBroadcast(true);
Log.v("MyDatagramReceiver", "Socket CREATED");
while (bKeepRunning) {
packet = new DatagramPacket(lmessage, lmessage.length);
Log.v("MyDatagramReceiver", "RECEIVING PACKET CREATED");
datagramsocket.receive(packet);
Log.v("MyDatagramReceiver", "PACKET RECEIVED");
message = new String(lmessage);
Log.v("MyDatagramReceiver", "Received packet contains:"
+ message);
ip = packet.getAddress();
Log.v("MyDatagramReceiver", "IP" + ip);
lastMessage = message;
Log.v("MyDatagramReceiver", "lastmessage contains:"
+ lastMessage);
String var = message;
Message completeMessage = mHandler.obtainMessage();
completeMessage.obj = var;
Log.v("MyDatagramReceiver", "completeMessage" + completeMessage);
completeMessage.sendToTarget();
byte[] m = "Hello_client".getBytes();
InetAddress aHost = InetAddress.getLocalHost();
DatagramPacket request = new DatagramPacket(m, m.length, ip,
port);
datagramsocket.send(request);
Log.v("MyDatagramReceiver", "Packet sent");
}
if (datagramsocket != null) {
datagramsocket.close();
}
} catch (Throwable e) {
e.printStackTrace();
}
}
public void kill() {
bKeepRunning = false;
}
public String getLastMessage() {
return lastMessage;
}
public static InetAddress getDeviceIP() {
if (Serverip != null) {
} else {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress intAdress = enumIpAddr.nextElement();
if (!intAdress.isLoopbackAddress()) {
if (intAdress instanceof Inet4Address) {
Serverip = intAdress;
Log.d("ServerIpHelper", "Client Ip Address: "
+ Serverip.getHostAddress().toString());
return Serverip;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return Serverip;
}
}