为什么在通过套接字写入发送时,图像不显示在客户端浏览器中?

时间:2015-08-31 12:30:07

标签: java sockets maven

我正在创建一个简单的HTTP服务器(使用maven)。当用户输入http://127.0.0.1:8181/pic时,应显示图像。

当我运行课程并输入http://127.0.0.1:8181/pic时,图像不会显示;我只是获得了垃圾字符行!

代码:

public static void main(String[] args) throws Exception {
    int port = 8181;

    ServerSocket server = new ServerSocket(port);
    System.out.println("Listening for a connection on port " + port + " ...");

    while (true) {
        Socket client = server.accept();
        System.out.println("A client connected: " + client.getInetAddress());

        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));

        String line = in.readLine();
        while (!line.isEmpty()) {
            System.out.println(line);

            String[] firstLine = line.split("\\s+"); // line is like: GET /pic HTTP/1.1
            String method = firstLine[0];

            if (method.equalsIgnoreCase("GET")) {

                String resourceNme = firstLine[1];

                if (resourceNme.equals("/pic")) {

                    out.write("Server: Apache/0.8.4\r\n");
                    out.write("Content-Type: text/html\r\n");
                    out.write("Content-type: image/gif");

                    out.write("\r\n");
                    out.write("<TITLE>Example Image</TITLE>");

                    //find file in system and send as response
                    URL url = SimpleHTTPServer.class.getResource("/office.jpg");
                    File file = new File(url.toURI());

                    if (file.exists()) {
                        System.out.println("file exists");
                        ImageInputStream imageInputStream = ImageIO.createImageInputStream(file);
                        long size = imageInputStream.length();

                        BufferedImage bufferedImage = ImageIO.read(file);
                        boolean success = ImageIO.write(bufferedImage, "jpeg", client.getOutputStream());
                        System.out.println("Success: " + success); // is true
                    } else {
                        System.out.println("don't exists");
                    }

                    out.close();
                    in.close();
                    client.close();
                    break;

                }
            }
        }
    }
}

收到样本输出:

SHùiƃ@8¤ÇîÔéHŽ”c­;… äúÑ“ëIŠ1@ËQ“ï@¥Å��œ÷¥Éõ¢Š�9õ¥Éõ¤¥ 'Ö€ÄzÑF(wzFb;ÑPÈø¤d”Œòj³HÄõ4®ù¨è»›ûÆÍýãIE�.æþñ£sxÒb—�noï7·÷£�ííêi|Æþñ¦âœ�Û?xÒïoïLRâ€
íýãNÞßÞ4ÜRâ€{xѽ¿¼i1F)�»›ûÆÍýãE�noSFæõ4bŒPîoïPíýãH ooï77÷ ¸ ÙûÆ—sxÓ@æ—�»›ûÆ—-ëMÅ--ýãFæõ4QŠ�]ÍêiK6:ÒRã4Ä"ï,�'šé4]5‹od•Ÿ§é­1G*H<×saf©œ`ŽÕ¤DÉ µÅXÆÓš~=iÈÅjf0¯9 ¨àŠv21@ 2äç¸ÈÎ)øãÆ)€ÜdRàÆ)zR‚E �7-�”v P�(�r)hÆ
0œbŒu¥ÆiHç4�˜”`n¥Åw Ú3JGJZ"€G|R°Î)våhÆåÅ�>ZR2™ |Ê>”ª3=)0
£f=©/ð§'+BŒ(c�¸¸Å‌

已移除与HTML相关的响应代码的已更新代码

                if (resourceNme.equals("/pic")) {
                    out.write("Server: Apache/0.8.4\r\n");
                    out.write("Content-type: image/jpeg\r\n");

                    URL url = SimpleHTTPServer.class.getResource("/office.jpg");
                    File file = new File(url.toURI());

                    if (file.exists()) {
                        System.out.println("file exists");
                        ImageInputStream imageInputStream = ImageIO.createImageInputStream(file);
                        long size = imageInputStream.length();
                        out.write("Content-Length: " + size + "\r\n");
                        out.write("\r\n");

                        BufferedImage bufferedImage = ImageIO.read(file);
                        boolean success = ImageIO.write(bufferedImage, "jpeg", client.getOutputStream());
                        System.out.println("Success: " + success); //true
                        out.close();
                        in.close();
                        client.close();
                        break;
                    } else {
                        System.out.println("don't exists");
                        out.close();
                        in.close();
                        client.close();
                        break;
                    }
                }

1 个答案:

答案 0 :(得分:1)

您将图片的文本和二进制数据直接发送到彼此后面。浏览器应该如何知道如何将两者分开?如果要组合HTML和图像,则HTML中应该有一个href = ...元素。如果您只想发送图片,请将内容类型设置为image / jpeg,但不能同时拥有两种内容类型。删除第一个内容类型行,删除包含TITLE的行。将您希望能够调用图像的URL更改为pic.jpg,它应该可以正常工作。