简体   繁体   中英

Using a common buffer to read from inputstream and to write to outputstream

I read from network socket's input stream into the buffer

count = input.read(buffer)

Then in next line, i'm printing the read contents using

str = new String(buffer,0,count);
Log.e("str",str);

Then i try to write it to a PipedOutputStream of an PipedInputStream

pipedOutputStream .write(buffer);

where,

pipedOutputStream = new PipedOutputStream(pipedInputStream)

The problem is the thread is blocking at pipedOutputStream .write(buffer);

Below is to confirm that, taken from Thread debugging tool of DDMS,

下图显示了DDMS线程查看器中引用的内容

  at java.lang.Object.wait(Native Method)   
  at java.lang.Object.wait(Object.java:401) 
  at java.io.PipedInputStream.receive(PipedInputStream.java:394)    
  at java.io.PipedOutputStream.write(PipedOutputStream.java:176)    
  at java.io.OutputStream.write(OutputStream.java:106)  
  at java.io.PipedOutputStream.write(PipedOutputStream.java:147)    
  at java.io.OutputStream.write(OutputStream.java:82)   
  at com.example.Receiver.run(DRCReceiver.java:104)

Can any one tell me, why the following is not working( blocking the thread ) (grouping all statements)

count = input.read(buffer)
str = new String(buffer,0,count);
Log.e("str",str);
pipedOutputStream .write(buffer);   

but the following is working( not blocking the thread ) .

count = input.read(buffer)
str = new String(buffer,0,count);
Log.e("str",str);
pipedOutputStream .write(str.getBytes());   

Thanks in advance

Have a look to JavaDoc . Here you can see: "Attempting to use both objects from a single thread is not recommended". Usually you need another thread that attempts to read some data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM