《服务器之间的图片传输 2023-12-19》模拟一台服务器(client)给另外一台服务(server)传输图片

Server

public class PictureTestServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(0)) {
            System.out.println("服务器已启动,监听端口: " + serverSocket.getLocalPort());
            Socket socket = serverSocket.accept();

            // 读取图片文件
            File file = new File("F:/picture/client/water.webp");
            try (FileInputStream fileInputStream = new FileInputStream(file);
                 DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {

                byte[] buffer = new byte[(int) file.length()];
                fileInputStream.read(buffer);

                // 发送图片文件到客户端
                dataOutputStream.write(buffer, 0, buffer.length);

                System.out.println("图片发送成功");
            }

            // 关闭套接字
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Client

public class PictureTestClient {
    public static void main(String[] args) {
        try {
        // 该端口为Server启动后监听的端口
            Socket socket = new Socket("localhost", 50966);

            // 从服务器接收图片文件
            InputStream inputStream = socket.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream("F:/picture/server/water.webp");

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

            System.out.println("图片接收成功");

            // 关闭流和套接字
            fileOutputStream.close();
            inputStream.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

先启动Server监听端口,获取到的端口替换掉Client端口,再启动Client端口
《服务器之间的图片传输 2023-12-19》模拟一台服务器(client)给另外一台服务(server)传输图片_第1张图片
《服务器之间的图片传输 2023-12-19》模拟一台服务器(client)给另外一台服务(server)传输图片_第2张图片

你可能感兴趣的:(服务器,图片传输)