码迷,mamicode.com
首页 > Web开发 > 详细

tcp图片上传

时间:2018-06-21 13:50:03      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:rgs   tcp   get   while   flush   shu   span   close   put   

1.client

 1 public static void main(String[] args) throws IOException {
 2         // 创建客户端Socket对象
 3         Socket s = new Socket("192.168.12.92", 19191);
 4 
 5         // 封装图片文件
 6         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
 7                 "林青霞.jpg"));
 8         // 封装通道内的流
 9         BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
10 
11         byte[] bys = new byte[1024];
12         int len = 0;
13         while ((len = bis.read(bys)) != -1) {
14             bos.write(bys, 0, len);
15             bos.flush();
16         }
17         
18         s.shutdownOutput();
19 
20         // 读取反馈
21         InputStream is = s.getInputStream();
22         byte[] bys2 = new byte[1024];
23         int len2 = is.read(bys2);
24         String client = new String(bys2, 0, len2);
25         System.out.println(client);
26 
27         // 释放资源
28         bis.close();
29         s.close();
30     }

 

2.server

public static void main(String[] args) throws IOException {
        // 创建服务器Socket对象
        ServerSocket ss = new ServerSocket(19191);

        // 监听客户端连接
        Socket s = ss.accept();

        // 封装通道内流
        BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
        // 封装图片文件
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream("mn.jpg"));

        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = bis.read(bys)) != -1) {
            bos.write(bys, 0, len);
            bos.flush();
        }

        // 给一个反馈
        OutputStream os = s.getOutputStream();
        os.write("图片上传成功".getBytes());

        bos.close();
        s.close();
    }

 

注意:IO流的操作流程不熟悉,查询api

tcp图片上传

标签:rgs   tcp   get   while   flush   shu   span   close   put   

原文地址:https://www.cnblogs.com/csslcww/p/9208352.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!