2
我有問題發送UDP的幾個數據是重複發送的最後一個發送多個數據對UDP套接字的Java的Android
UDP_Client Client = new UDP_Client();
Client.Message = "Your message1";
Client.NachrichtSenden();
Client.Message = "Your message2";
Client.NachrichtSenden();
Client.Message = "Your message3";
Client.NachrichtSenden();
輸出
你MESSAGE3
你message3
您的留言3
我使用這個源
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Build;
public class UDP_Client
{
private AsyncTask<Void, Void, Void> async_cient;
public String Message;
@SuppressLint("NewApi")
public void NachrichtSenden()
{
async_cient = new AsyncTask<Void, Void, Void>()
{
@Override
protected Void doInBackground(Void... params)
{
DatagramSocket ds = null;
try
{
ds = new DatagramSocket();
DatagramPacket dp;
dp = new DatagramPacket(Message.getBytes(), Message.length(), Main.BroadcastAddress, Main.SERVER_PORT);
ds.setBroadcast(true);
ds.send(dp);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (ds != null)
{
ds.close();
}
}
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
};
if (Build.VERSION.SDK_INT >= 11) async_cient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else async_cient.execute();
}
}
(形式:Send and receive data on UDP Socket java android)