vendredi 6 mars 2015

UDP packet is not sent



Here is my class:



public class DatagramClient
{
private DatagramSocket socket = null;
InetAddress h;
public DatagramClient() throws SocketException, IOException {
try {
socket = new DatagramSocket();
socket.setBroadcast(true);
h = InetAddress.getByName("192.168.2.108");

}
catch (Exception e) {
Log.i(Constantes.TAG_LOG, e.getMessage());
}
}

public DatagramSocket getSocket() {
return socket;
}

public void setSocket(DatagramSocket socket) {
this.socket = socket;
}

public void sendPacket(String msg){
byte[] data = msg.getBytes();
Log.i(Constantes.TAG_LOG,"Criar DatagramPacket");
final DatagramPacket packet = new DatagramPacket(data,data.length,h,Constantes.UDP_PORT);
Log.i(Constantes.TAG_LOG,"Criou DatagramPacket");
Log.i(Constantes.TAG_LOG,"Enviar packet");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Log.i(Constantes.TAG_LOG,"Run Thread");
socket.send(packet);
Log.i(Constantes.TAG_LOG,"Envio dentro da thread");
} catch (IOException e) {
e.printStackTrace();
}
}
});

Log.i(Constantes.TAG_LOG,"Enviou fora da thread");
}

}


I need send a UDP packet as the string parameter in sendPacket method. When I look at the logcat output I don't see any errors, but the UDP packet is not sent. What is going wrong here?


I added this code and doesn't work:



try {
thread.start();
Log.i(Constantes.TAG_LOG,"Executou thread");
}catch(Exception e){
Log.i(Constantes.TAG_LOG,"Erro thread.start()"+e.getMessage());
}


logcat>



03-06 21:16:07.814 1199-1199/com.pa.homeautomation I/HOME_AUTOMATION﹕ Criar DatagramPacket
03-06 21:16:07.814 1199-1199/com.pa.homeautomation I/HOME_AUTOMATION﹕ Criou DatagramPacket
03-06 21:16:07.814 1199-1199/com.pa.homeautomation I/HOME_AUTOMATION﹕ Enviar packet
03-06 21:16:07.814 1199-1199/com.pa.homeautomation I/HOME_AUTOMATION﹕ Executou thread
03-06 21:16:07.814 1199-1199/com.pa.homeautomation I/HOME_AUTOMATION﹕ Enviou fora da thread
03-06 21:16:07.814 1199-1199/com.pa.homeautomation I/HOME_AUTOMATION﹕ Send PEDRO
03-06 21:16:07.814 1199-2173/com.pa.homeautomation I/HOME_AUTOMATION﹕ Run Thread
03-06 21:16:07.814 1199-2173/com.pa.homeautomation I/HOME_AUTOMATION﹕ Envio dentro da thread
03-06 21:16:08.324 1199-1199/com.pa.homeautomation I/HOME_AUTOMATION﹕ Criar DatagramPacket
03-06 21:16:08.324 1199-1199/com.pa.homeautomation I/HOME_AUTOMATION﹕ Criou DatagramPacket
03-06 21:16:08.324 1199-1199/com.pa.homeautomation I/HOME_AUTOMATION﹕ Enviar packet
03-06 21:16:08.324 1199-1199/com.pa.homeautomation I/HOME_AUTOMATION﹕ Executou thread
03-06 21:16:08.324 1199-1199/com.pa.homeautomation I/HOME_AUTOMATION﹕ Enviou fora da thread
03-06 21:16:08.324 1199-1199/com.pa.homeautomation I/HOME_AUTOMATION﹕ Send PEDRO
03-06 21:16:08.324 1199-2175/com.pa.homeautomation I/HOME_AUTOMATION﹕ Run Thread
03-06 21:16:08.324 1199-2175/com.pa.homeautomation I/HOME_AUTOMATION﹕ Envio dentro da thread



Aucun commentaire:

Enregistrer un commentaire