• 周四. 4月 18th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

java 26

admin

11月 28, 2021

上次的是上传TXT文件,这次上传的是图片。同样,上传成功需要反馈给客户端。

区别:

  TXT文件用记事本打开,我们可以看得懂,所以用了缓冲字符流,对通道内的字节流进行包装了。

  而图片用记事本打开,我们看不懂,所以就用缓冲字节流,只需要把通道内的字节流转换成高效字节流就可以了。

客户端:

  

 1 public class ClineDemo {
 2     public static void main(String[] args) throws IOException {
 3 
 4         // 创建Socket对象
 5         Socket s = new Socket("172.19.12.233", 10010);
 6 
 7         // 封装图片,图片只能使用字节流,为了高效,用缓冲字节流
 8         BufferedInputStream bi = new BufferedInputStream(new FileInputStream(
 9                 "java程序员.jpg"));
10 
11         // 把通道中的字节流包装成缓冲字节流
12         BufferedOutputStream bo = new BufferedOutputStream(s.getOutputStream());
13 
14         // 接收图片,并发送给服务器
15         byte[] bys = new byte[1024];
16         int len = 0;// 读取的实际长度,没有数据时,为-1
17         while ((len = bi.read(bys)) != -1) {
18             bo.write(bys, 0, len);
19             bo.flush();
20         }
21 
22         // 提醒服务器已经读取完毕,终止
23         s.shutdownOutput();
24 
25         // 接收反馈
26         InputStream in = s.getInputStream();
27         byte[] by = new byte[1024];
28         //肯定有内容的,就不判断了
29         int len1 = in.read(by);
30         String str = new String(by,0,len1);
31         System.out.println(str);
32 
33         // 释放资源
34         bi.close();
35         s.close();
36     }
37 }

服务器:

 1 public class ServerDemo {
 2     public static void main(String[] args) throws IOException {
 3 
 4         // 创建ServerSocket对象,监听
 5         ServerSocket ss = new ServerSocket(10010);
 6 
 7         // 创建Socket对象
 8         Socket s = ss.accept();
 9 
10         // 把通道中的字节流转成缓冲字节流
11         BufferedInputStream bi = new BufferedInputStream(s.getInputStream());
12 
13         // 封装图片目录
14         BufferedOutputStream bo = new BufferedOutputStream(
15                 new FileOutputStream("java.jpg"));
16 
17         // 获取图片的数据,并输出
18         byte[] bys = new byte[1024];
19         int len = 0;
20         while ((len = bi.read(bys)) != -1) {
21             bo.write(bys, 0, len);
22             bo.flush();
23         }
24         
25         //给客户端反馈
26         OutputStream op = s.getOutputStream();
27         op.write("图片上传成功".getBytes());
28         
29         //释放资源
30         s.close();
31         bo.close();
32 
33     }
34 }

《java 26》有2个想法
  1. Wow, amazing blog structure! How lengthy have you ever been running a blog
    for? you make blogging look easy. The overall look of your website is excellent,
    as neatly as the content! You can see similar here ecommerce

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注