tcp图片上传

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

posted @ 2018-06-21 12:12  深沉有点事  阅读(791)  评论(0编辑  收藏  举报