网络编程(客户端,服务端文件上传下载)

服务端

  • 可以接收多个客户端请求
  • 使用多线程实现
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(8888);
        while (true){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        Socket socket = serverSocket.accept();
                        BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
                        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("/Users/mima000000/Desktop/"+System.currentTimeMillis()+".jpeg"));
                        int len;
                        byte[] bytes = new byte[1024*8];
                        while ((len=bufferedInputStream.read(bytes))!=-1){
                            bufferedOutputStream.write(bytes,0,len);
                        }
                        System.out.println("文件上传成功");
                        OutputStream outputStream = socket.getOutputStream();
                        outputStream.write("上传成功".getBytes());
                        outputStream.close();
                        bufferedOutputStream.close();
                        socket.close();
                    }catch (Exception e){
                        System.out.println(e);
                    }
                    

                }
            }).start();
            
        }


    }
}

客户端

import java.io.*;
import java.net.Socket;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 8888);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("/Users/mima000000/Desktop/1.jpeg"));
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
        int len;
        byte[] temp = new byte[1024];
        while ((len=bufferedInputStream.read(temp))!=-1){
            bufferedOutputStream.write(temp,0,len);
        }
        socket.shutdownOutput(); // 表示通知服务端,写出完毕结束。
        System.out.println("fild upload successful");
        InputStream inputStream = socket.getInputStream();
        byte[] arr = new byte[20];
        inputStream.read(arr);
        System.out.println(new String(arr));

        inputStream.close();
        bufferedInputStream.close();
        socket.close();

    }
}

posted @ 2020-03-15 23:06  姚狗蛋  阅读(216)  评论(0编辑  收藏  举报