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();
    }

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

原文地址:https://www.cnblogs.com/zhangzhixi/p/14191788.html