zoukankan      html  css  js  c++  java
  • socket简单示例实现从服务器拷贝文件到客户端

    读写工具类
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.IOException;
    
    public class MyUtil {
        /**
         *
         * @param bis 缓存字节输入流
         * @param bos 缓存字节输出流
         * @throws IOException 抛出异常,IO流读写过程中可能发生异常
         */
        public static void readAndWriter(BufferedInputStream bis, BufferedOutputStream bos) throws IOException {
            // 定义长度为1024的字节数组
            byte [] bytes = new byte [1024];
            int c = 0;
            while((c = bis.read(bytes))!=-1){//组合式写法
                //写入到文件
                bos.write(bytes, 0, c);
            }
            //关闭流,一定要关闭流,节约资源
            bos.close();
            bis.close();
        }
    }
    
    
    服务器
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class MyServer {
        public static void main(String[] args) throws IOException {
            //1.创建server,自定义端口号
            ServerSocket server = new ServerSocket(1689);
            //2.监听
            Socket socket = server.accept();
            //3.通过socket读取网络文件
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            //4.写入到本地文件
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:/1.txt"));
            //5.边读边写
            //读取的中转站
            MyUtil.readAndWriter(bis,bos);
        }
    }
    
    
    客户端
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.Socket;
    
    public class MyClient {
        public static void main(String[] args) throws IOException {
            // 创建socket和server进行连接,连接服务器的端口号
            Socket socket = new Socket(InetAddress.getLocalHost(),1689);
            // 读取文件
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("F:/Music/A Fine Keturns-- 《New World M.mp3"));
            // 写入到网络中
            BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
            MyUtil.readAndWriter(bis,bos);
        }
    }
     
  • 相关阅读:
    HTML 特殊符号编码对照表
    C#删除字符串最后一个字符的几种方法
    c# 获取相对路径
    垂直滚动条代码
    Android微信分享功能实例+demo
    android之Itent.ACTION_PICK Intent.ACTION_GET_CONTENT妙用
    Android Camera 使用小结
    onSaveInstanceState和onRestoreInstanceState
    Android中的PopupWindow详解
    Unable to execute dex: java.nio.BufferOverflowException.解决办法
  • 原文地址:https://www.cnblogs.com/givre-foudre/p/12343460.html
Copyright © 2011-2022 走看看