zoukankan      html  css  js  c++  java
  • 04-TCP下载资源的实现

    TCP服务器端:

    public static void main(String[] ars) throws Exception {
            //1、创建服务
            ServerSocket ss = new ServerSocket(8888);
            //2、监听客户端连接
            Socket socket = ss.accept();
            //3、获取输入流
            InputStream is = socket.getInputStream();
    
            //4、文件输出
            FileOutputStream fos = new FileOutputStream(new File("demo.jpg"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
            is.close();
            ss.close();
            socket.close();
            ss.close();
        }

    TCP客户端:

    public static void main(String[] args) throws Exception {
            //1、创建一个连接
            Socket socket = new Socket(InetAddress.getByName("localhost"), 8888);
            //2、创建输出流
            OutputStream os = socket.getOutputStream();
            //3、读取文件
            FileInputStream fis = new FileInputStream(new File("src/com/zhixi/TCP实现文件的上传和下载/二次元.jpg"));
            //4、写出文件
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes,0,len);
            }
            fis.close();
            os.close();
            socket.close();
        }

    开启服务器,开启客户端,就会把项目资源下的文件进行下载了:

  • 相关阅读:
    [ZJOI2010]基站选址
    [SDOI2008]Sue的小球
    访问计划
    奥义商店
    codeforces 809E Surprise me!
    codeforces 888G Xor-MST
    [HAOI2015]数字串拆分
    小奇分糖果
    小奇的花园
    BZOJ4711 小奇挖矿
  • 原文地址:https://www.cnblogs.com/zhangzhixi/p/14191788.html
Copyright © 2011-2022 走看看