BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(reader.readLine());
为什么我上面读不到数据,而下面的可以?
byte[] buf = new byte[1024];
int len = 0;
InputStream input = socket.getInputStream();
while((len = input.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
我在网上看到好多字符串尽量用缓冲流,可以有时候为什么缓冲流得不到数据,而必须用原生的String,求指教
socketstring

解决方案 »

  1.   

    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     System.out.println(reader.readLine());
    这个是按行读取必须有换行符 '\n'InputStream input = socket.getInputStream();
     while((len = input.read(buf))!=-1){
     System.out.println(new String(buf,0,len));
     }
    这个是字节流的方式,显然能读,读到缓冲区继续循环 直到通道中的流没有了。
      

  2.   

    public static byte[] readInputStream(InputStream ins) {     BufferedInputStream bis = new BufferedInputStream(ins);  
      ByteArrayOutputStream bos = new ByteArrayOutputStream();  
       try {  
           byte[] buffer = new byte[128];  
           int n = -1;  
           while ((n = bis.read(buffer)) != -1) {  
               bos.write(buffer, 0, n);  
           }  
       } catch (IOException e) {  
            e.printStackTrace();  
          return null;  
       } finally {  
           if (bis != null) {  
              try {  
                   bis.close();  
                } catch (IOException e) {  
                   e.printStackTrace();  
                }  
            }  
        }  
        return bos.toByteArray();  
    }  
    能完整的读完IO流。尽量不要用字符流,一行行的读取,需要对方发送\n符号,才能读取。
      

  3.   

    发了.我用
    InputStream input = socket.getInputStream();
     while((len = input.read(buf))!=-1){
     System.out.println(new String(buf,0,len));
     }
    能收到数据啊