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

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

  • 相关阅读:
    linux读写锁
    正则表达式
    C++原型模式和模板模式
    C++外观模式和组合模式
    C++代理模式
    c++桥接模式
    Linux常用命令history/tcpdump/awk/grep
    C++委托模式
    c++ 读写锁
    布衣客
  • 原文地址:https://www.cnblogs.com/zhangzhixi/p/14191788.html
Copyright © 2020-2023  润新知