java - How to use correctly InputStream.read(buffer) method and process my Data? -
i have create application in android connect galaxy s3 device, in answer call device1. use socket , inputstream. - first: connect phone using socket, when connection established, device1 send me string store in 1 buffer.
- second: send device1 "s" string, when device1 receive string, send me continuos data without interruption.
-tree: want read data , elaboration
the problem inputstream.read(buffer) blocking, receive data i'm not able processing it.
here code:
public void run() { try { socket=new socket(); socket.connect(new inetsocketaddress(ipdevice,portdevice),20); //settare il timeout per evitare che tutto si blocchi su receive string controllo="connesso"; showtoast(controllo); inputstream = socket.getinputstream(); byte[] buffer_controllo = new byte[1024]; int count_bytes_read; char[] chars ; string str; count_bytes_read = is.read(buffer_controllo); //lettura del buffer str=new string(buffer_controllo); chars=new char[count_bytes_read]; outputstreamwriter osw = new outputstreamwriter(socket.getoutputstream()); bufferedwriter bw = new bufferedwriter(osw); printwriter out = new printwriter(bw, true); out.write("s"); byte[] buffer_dati = new byte[1024]; int count_bytes_read2=0; while(count_bytes_read2!=-1){ count_bytes_read2 = is.read(buffer_dati); //problem here } str=new string(buffer_dati); chars=new char[count_bytes_read]; } catch (unknownhostexception e) { // todo auto-generated catch block string controllo="non connesso"; showtoast(controllo); try { socket.close(); } catch (ioexception e1) { // todo auto-generated catch block e1.printstacktrace(); } e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block string controllo="non connesso"; showtoast(controllo); try { socket.close(); } catch (ioexception e1) { // todo auto-generated catch block e1.printstacktrace(); } e.printstacktrace(); } finally{ if(socket!=null){ try { outputstreamwriter osw = new outputstreamwriter(socket.getoutputstream()); bufferedwriter bw = new bufferedwriter(osw); printwriter out = new printwriter(bw, true); out.write("z"); out.flush(); socket.close(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } } } }); //avvio del thread cthread.start();
as can see problem here:
count_bytes_read2 = is.read(buffer_dati);
this read method blocking, receive infinite number of data device1, can't take buffer dati , doing elaboration on it. how can take data during execution of read method? have block read time or there other solution? thank you.
datafetcher class wrote handle these sorts of issues. it's threaded reader operates through listener/callback pattern... though can used read stream fully. think useful in solving problem
Comments
Post a Comment