以下是用Java实现针对所有后缀名为.jpg的请求都返回同一张图片的代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ImageServer {

    public static void main(String[] args) throws IOException {
        int port = 8000;
        String imagePath = "path/to/image.jpg";
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Server started on port " + port);

        while (true) {
            Socket clientSocket = serverSocket.accept();
            System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());

            String request = getRequest(clientSocket.getInputStream());
            if (request.contains(".jpg")) {
                sendImage(imagePath, clientSocket.getOutputStream());
            } else {
                send404(clientSocket.getOutputStream());
            }

            clientSocket.close();
        }
    }

    private static String getRequest(InputStream inputStream) throws IOException {
        StringBuilder sb = new StringBuilder();
        int c;
        while ((c = inputStream.read()) != -1 && c != '\r') {
            sb.append((char) c);
        }
        return sb.toString();
    }

    private static void sendImage(String imagePath, OutputStream outputStream) throws IOException {
        File file = new File(imagePath);
        byte[] data = new byte[(int) file.length()];
        FileInputStream fileInputStream = new FileInputStream(file);
        fileInputStream.read(data);
        fileInputStream.close();

        String contentType = "Content-Type: image/jpeg\r\n";
        String contentLength = "Content-Length: " + data.length + "\r\n";
        String response = "HTTP/1.1 200 OK\r\n" + contentType + contentLength + "\r\n";
        outputStream.write(response.getBytes());
        outputStream.write(data);
    }

    private static void send404(OutputStream outputStream) throws IOException {
        String response = "HTTP/1.1 404 Not Found\r\n\r\n";
        outputStream.write(response.getBytes());
    }

}

这段代码使用了Socket编程,监听8000端口,当有客户端连接时,读取请求,如果请求中包含.jpg后缀,则返回指定路径下的图片,否则返回404错误

用java写一段代码实现针对所有后缀名为jpg的请求都返回同一张图片

原文地址: http://www.cveoy.top/t/topic/c4jn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录