几天前,我考虑编写自己的图像客户端以通过 HTTP 直接传输图像。我用谷歌搜索并研究了一段时间并编写了我的服务器:
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;
}
}
}
主类是一个等待接受许多连接的线程,将它们存储在 ArrayList 中,创建 SConnection 实例并启动它们。
客户端看起来像这样:
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);
服务器和客户端都发送位于 ImageIO.write / ImageIO.read - 行的异常。
服务员说:
java.net.SocketException: Connection reset by peer: socket write error
客户说:
java.io.IOException: Invalid Http response
我明白了,图像没有正确传输,但我应该改变什么?有什么线索吗?
谢谢各位,提前!