这一直困扰着我一段时间,我不太确定如何解决这个问题。
我遇到的问题是在服务器实际接收数据包之前需要多次尝试推送数据包
这是我在客户端上的代码(服务器是相同的,但发送/接收是相反的),服务器从数据包中获取客户端 IP 以发送返回数据包
class MainTask extends AsyncTask<Void, Void, Void> {
ProgressDialog progress = null;
Context context = null;
public MainTask(ProgressDialog progress, Context context) {
this.progress = progress;
this.context = context;
}
public void onPreExecute() {
progress.show();
}
public Void doInBackground(Void... unused) {
// Send UDP Packet
String messageStr="Hello Android!";
int server_port = 12441;
DatagramSocket s = null;
DatagramPacket p = null;
InetAddress local = null;
Log.i("EyeceBoxService", "Sending packet");
try {
s = new DatagramSocket();
local = InetAddress.getByName("192.168.0.4");
int msg_length=messageStr.length();
byte[] message = messageStr.getBytes();
p = new DatagramPacket(message, msg_length,local,server_port);
s.send(p);
Log.i("EyeceBoxService", "Packet Sent!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Receive UDP Packet
byte[] message = new byte[1500];
try {
//progress.setMessage("Retrieving Discovery Information...");
p = new DatagramPacket(message, message.length);
s = new DatagramSocket(server_port);
Log.i("EyeceBoxService", "Waiting for packet");
s.receive(p);
String address = p.getAddress().toString();
Log.i("EyeceBoxService", "Server IP address" + address);
//progress.setMessage("Done...");
//MainActivity.buildNotification(context, address);
progress.dismiss();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void onPostExecute(Void unused) {
}
}