java网络编程TCP传输—流操作—拿到源后的写入动作

  在网络编程中的TCP传输里,拿到Socket的源后,应该怎么进行读写操作呢,下面我列举了两种方法,希望大家帮忙补充····

1.利用byte数组作为一个缓冲区进行读写

 

客户端上传

 1 //获取socket流,将图片上传给服务端
 2         FileInputStream fis=new FileInputStream("c:\\12.jpg");
 3         
 4         //获取了输出流
 5         OutputStream out=s.getOutputStream();
 6         
 7         //用数组作为缓冲
 8         byte[]buf=new byte[1024];
 9         
10         //len用来记录长度
11         int len=0;
12         
13         //循环读写
14         while((len=fis.read(buf))!=-1){
15             //当返回-1时表示读完毕,此时len为总长度
16             out.write(buf,0,len);
17         }

//服务端接收时

1
InputStream in=s.getInputStream(); 2 File dir=new File("c:\\pic"); 3 if(!dir.exists()){ 4 dir.mkdirs(); 5 } 6 FileOutputStream fos=new FileOutputStream("server.jpg"); 7 byte[] buf=new byte[1024]; 8 int len=0; 9 while((len=in.read())!=-1){ 10 fos.write(buf,0,len); 11 } 12

 服务端接收(不需要写入文件中时) 

1 byte [] buf=new byte[1024];
2         //此时只需要或取长度就可以了
3         int len=in.read(buf);
4         //直接用数组获取文本就可以了
5         String text=new String(buf,0,len);

 

 

 

2.使用缓冲区作为缓冲

 1       //客户端上传

      //使用流输出数据
       BufferedReader bufr=new BufferedReader(new FileReader("client.txt")); 2 3 //通过使用PrintWriter对字节流和字符流进行处理,接管流 4 PrintWriter out =new PrintWriter(s.getOutputStream(),true); 5 6 //开始读取,上传给服务端 7 String line=null; 8 while((line=bufr.readLine())!=null){ 9 out.println(line); 10 }
 1       //服务端接收

  
      //将接收的数据放入流中 2 BufferedReader bufIn= 3 new BufferedReader(new InputStreamReader(s.getInputStream())); 4 5 //指定要写入得文件 6 BufferedWriter bufw=new BufferedWriter(new FileWriter("server.txt")); 7 8 //开始读取 9 //缓冲区的默认大小为8k,一到8k则会自动刷新,若没有结束标志,则得到的文件大小一定是8的倍数 10 String line=null; 11 while((line=bufIn.readLine())!=null){ 12 if("over".equals(line)) 13 break; 14 bufw.write(line); 15 bufw.newLine(); 16 //自己写刷新 17 bufw.flush(); 18 } 19

 

posted @ 2016-06-28 20:01  因吹斯汀  阅读(598)  评论(0编辑  收藏  举报