简体   繁体   English

Java Image Server:套接字写入错误

[英]Java Image Server: socket write error

A couple of days ago I thought about programming my own image client to transfer images directly via the HTTP. 几天前,我考虑过对自己的图像客户端进行编程以直接通过HTTP传输图像。 I googled and researched quite some time and wrote my server: 我用谷歌搜索并研究了一段时间,并编写了服务器:

public class SConnection extends Thread {

    Socket client;

    /* ... */

    @Override
    public void run() {

        while(true) {
            try {

                //Get some image paths
                File folder = new File(new java.net.URI("file:///C:/images/"));
                File[] images = folder.listFiles();
                //Load the image
                BufferedImage bi = ImageIO.read(images[0]);
                //Write the image
                ImageIO.write(bi, "JPEG", client.getOutputStream());

            } catch (Exception ex) {

                ex.printStackTrace();
                return;

            }

        }

    }

The main class is a Thread waiting to accept many connections, storing them in an ArrayList, creating instances of SConnection and starting them. 主要类是一个线程,它等待接受许多连接,将它们存储在ArrayList中,创建SConnection实例并启动它们。

The client looks like this: 客户看起来像这样:

URL target = new URL("http://127.0.0.1:82"); //The server - so far, so good
URLConnection conn = target.openConnection();
BufferedImage in = ImageIO.read(conn.getInputStream()); //And as I try to receive the image: boom, exception
File save = new File(new java.net.URI("file:///C:/images/result.jpeg"));
ImageIO.write(in, "JPEG", save);

Server and client both send Exceptions located at the ImageIO.write / ImageIO.read - lines. 服务器和客户端都发送位于ImageIO.write / ImageIO.read-行的异常。

The server says: 服务器说:

java.net.SocketException: Connection reset by peer: socket write error

The client says: 客户说:

java.io.IOException: Invalid Http response

I get, that the image is not transferred correctly, but what should I change? 我得到的图像传输不正确,但是我应该怎么做? Any clues? 有什么线索吗?

Thanks you guys, in advance! 谢谢你们,提前!

  1. You don't appear to be writing HTTP headers, so the client URLConnection won't understand the reply and will close the connection, causing 'connection reset by peer' at the sender. 您似乎没有编写HTTP标头,因此客户端URLConnection无法理解答复,因此将关闭连接,从而导致发送方发生“对等方重置连接”。

  2. You don't need to construct a URI to open a file. 您无需构造URI即可打开文件。

  3. You don't need to use ImageIO at all. 您根本不需要使用ImageIO。 This just wastes time and space. 这只是浪费时间和空间。 Just copy the bytes, like any other file type. 就像其他文件类型一样,只需复制字节即可。

In short you don't really need this code at all. 简而言之,您根本不需要此代码。 The default servlet will do it for you. 默认的servlet将为您完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM