c# - How to solve my android Udp socket doesn't receive the packet sometime? -
firstly,i know risk of using udp socket instead of tcp.
i send image client c# server androids listening port using udp socket.
the problem can sometime receive packet in first attempt of sending( note :run c# console image sending app). sometime, have try more 1 attempts of sending in order receive it.
any or ideas appreciated. in advance
c# client code
const int port = 4800; string serverip = "?"; //get addresses string hostname = system.net.dns.gethostname(); iphostentry alllocalnetworkaddresses = dns.resolve(hostname); //walk thru network interfaces. foreach (ipaddress ip in alllocalnetworkaddresses.addresslist) { socket client = new socket(addressfamily.internetwork, sockettype.dgram, protocoltype.udp); //allow sending broadcast messages client.setsocketoption(socketoptionlevel.socket, socketoptionname.broadcast, 1); //bind on port 0. os give port between 1025 , 5000. client.bind(new ipendpoint(ip, 0)); //create endpoint, broadcast. ipendpoint allendpoint = new ipendpoint(ipaddress.broadcast, port); string path = "d:\\download.jpg"; filestream fs = new filestream(path, filemode.open, fileaccess.read); binaryreader br = new binaryreader(fs); byte[] data = br.readbytes(convert.toint16(fs.length)); client.sendto(data, allendpoint); console.write("client send 'image' " + allendpoint.tostring() + environment.newline); }
android server
protected string doinbackground(string... arg0) { final textview text2 = (textview) findviewbyid(r.id.textview2); try { socket = new datagramsocket(port); int buf= socket.getreceivebuffersize(); byte[] receivedata = new byte[buf]; while (true) { final datagrampacket recv_packet = new datagrampacket(receivedata, receivedata.length); log.d("udp", "s: receiving..."); socket.receive(recv_packet); byte[] buff = recv_packet.getdata(); final bitmap new_img = bitmapfactory.decodebytearray(buff, 0, buff.length); runonuithread(new runnable() { @override public void run() { text2.settext("now connected"); imageview image = (imageview) findviewbyid(r.id.imageview); image.setimagebitmap(new_img); } }); } } catch (exception e) { log.e("udp", "s: error", e); runonuithread(new runnable() { @override public void run() { //tv.settext("error occured"); } }); } return text1; }
Comments
Post a Comment