Android Datagram Sockets not working -
i trying implement basic datagram sockets in android. starting 1 of samples available on web:
string messagestr="hello android!"; int server_port = 54372; try { datagramsocket s = new datagramsocket(); inetaddress local = null; local = inetaddress.getbyname("192.168.100.127"); int msg_length=messagestr.length(); byte[] message = messagestr.getbytes(); datagrampacket p = new datagrampacket(message, msg_length, local, server_port); s.send(p); } catch (socketexception e) { e.printstacktrace(); } catch (unknownhostexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); }
i have enables internet permissions in androidmanifest.xml:
<uses-permission android:name="android.permission.internet"/>
the program dies when hits s.send(p)
command.
what missing? must obvious.
you getting error not catch-ing: networkonmainthreadexception. should networking staff in thread or asynctask.
for example:
class mythread extends thread { @override public void run() { udpsend(); } void udpsend() { string messagestr = "hello android!"; int server_port = 54372; try { datagramsocket s = new datagramsocket(); inetaddress local = null; local = inetaddress.getbyname("192.168.1.57"); int msg_length = messagestr.length(); byte[] message = messagestr.getbytes(); datagrampacket p = new datagrampacket(message, msg_length, local, server_port); s.send(p); android.util.log.w("udp", "works fine!"); } catch (socketexception e) { e.printstacktrace(); } catch (unknownhostexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } catch (exception e) { android.util.log.w("udp", "catched here."); e.printstacktrace(); } } }
to execute thread in main thread: new mythread().start();
update:
udp receiver in asynctask: real example of app. i've removed lines not relevant. show doinbackgroud, 1 receive udp packets.
@override protected void doinbackground(void... urls) { datagramsocket socketudp; try { socketudp = new datagramsocket(5050); socketudp.setsotimeout(5000); // set true if want receive broadcast packets socketudp.setbroadcast(false); } catch (exception e) { e.printstacktrace(); return null; } byte[] buff = new byte[512]; datagrampacket packet = new datagrampacket(buff, buff.length); try { asynctask_udp_is_running=true; // keep running until application gets inactive while (aplicationactive) { try { socketudp.receive(packet); android.util.log.w("udp", "got packet"); } catch (java.net.sockettimeoutexception ex) { // timeout } catch (exception e) { e.printstacktrace(); return null; } } } { asynctask_udp_is_running=false; } return null; }
}
Comments
Post a Comment