java【Socket】【上传下载文件】

public class TCPClient {
    public static void main(String[] args)throws IOException {
        Socket socket = new Socket("127.0.0.1",5000);
        OutputStream out = socket.getOutputStream();
        //创建文件对象     如果文件路径写错   Client报找不到文件异常,Server报Connection Reset异常
        File file = new File("E:\\Pictures\\010.jpg");  
        //字节输入流,读取本地文件到java程序中
        FileInputStream fis = new FileInputStream(file);
        byte[] data = new byte[1024];              //数组,增强传输效率
        int len = 0;
        while((len = fis.read(data)) != -1)   //read方法返回数组的有效字符个数
            out.write(data, 0, len);                              
        socket.shutdownOutput();  //数据传输完毕,关闭socket输出流,避免服务器端read方法阻塞

        InputStream in = socket.getInputStream();      //字节输入流,读取服务器返回的数据
        len = in.read(data);
        System.out.println(new String(data,0,len));

        socket.close();
        fis.close();
    }

   }



   public class TCPServer {
    public static void main(String[] args)throws IOException {
        ServerSocket server = new ServerSocket(5000);//打开服务器制定端口,等待客户端连接
        //获得与服务器相连的套接字对象     套接字:绑定ip地址和端口号的网络对象
        Socket socket = server.accept();
        //查看该地址文件夹是否存在,如果不存在,创建一个
        File file = new File("E:\\TestFolder\\upload"); 
        if(!file.exists()){
            boolean b = file.mkdirs();
            System.out.println(b);
        }   
        InputStream in = socket.getInputStream();  //套接字的字节输入流,读取客户端传过来的数据

        String name = System.currentTimeMillis()+""+new Random().nextInt(9999);        //随机文件名
        FileOutputStream fos = new FileOutputStream(file+File.separator+name+".jpg");  //File.separator表示分隔符,windows是\,linux是/             
        byte[] data = new byte[1024];
        int len = 0;
//如果客户端没有关闭socket输出流,这里的read方法会一直读取,对于socket流没有流末尾之说,不可能返回-1
        while((len = in.read(data)) != -1)  
            fos.write(data, 0, len);
        data = "上传成功!".getBytes();      //字符串转化为字节数组
        OutputStream out = socket.getOutputStream();     //创建字节输出流
        out.write(data);                //写入上传成功  ,反馈给客户端   
        server.close();
        fos.close();
    }

}

posted @ 2021-11-24 13:32  该显示昵称已被使用了  阅读(152)  评论(0)    收藏  举报