Java:使用套接字从客户端向服务器发送多个映像文件

时间:2012-04-04 09:52:31

标签: java sockets file-io

我想从客户端向服务器发送多个图像文件,为此我在我的应用程序中编写代码,但它只发送一个图像。 在客户端应用程序中有一帧,在服务器应用程序中也有一个框架来启动/停止服务器。

还有一个问题是,当客户端应用程序发送图像文件然后显示在服务器计算机上的此图像文件但是当我尝试打开此图像文件时,没有任何东西,但当我关闭服务器应用程序(服务器框架)然后我能够看图像。

代码:

客户端网站:

public void sendPhotoToServer(String str){ // str is image location
    try {
        InputStream input = new FileInputStream(str);
        byte[] buffer=new byte[1024];
        int readData;
        while((readData=input.read(buffer))!=-1){
        dos.write(buffer,0,readData); // dos is DataOutputStream
        }
    } catch (FileNotFoundException e) {

    } catch (IOException e) {

    }       
}

在服务器端,此代码正在运行到线程中:

public void run() {
while (true) {
            try {
                byte[] buffer = new byte[8192];
                fis = new FileOutputStream("C:\\"+(s1++)+".jpg"); // fis is FileOutputStream
                while ((count = in.read(buffer)) > 0){ //count is a integer and 'in' is InputStream
                fis.write(buffer, 0, count); 
                fis.flush();    
                }
                } catch (Exception e) {}
}
}

问题:

  1. 只有第一张图片是客户发送的复印件。
  2. 只有在关闭服务器应用程序时才能看到此图像。
  3. 没有异常,我连续在其他类中调用 sendPhotoToServer 方法将所有图像文件发送为:

    if (photoSourcePath != null) {
                                clientClass.sendPhotoToServer(photoSourcePath+"\\"+rowData.get(5));
                            }
    

1 个答案:

答案 0 :(得分:0)

您的服务器端应该在其作业完成后停止该线程。 while循环只是永远保持运行并保持流打开(这就是当你关闭服务器时看到图像的原因,线程只会停止)。

尝试将服务器端更改为:

public void run() {
    boolean processing = true;
    while (processing) {
        try {
            byte[] buffer = new byte[8192];
            fis = new FileOutputStream("C:\\" + (s1++) + ".jpg"); // fis is
                                                                  // FileOutputStream
            while ((count = in.read(buffer)) > 0) { // count is a integer
                                                    // and 'in' is
                                                    // InputStream
                fis.write(buffer, 0, count);
                fis.flush();

            }
            processing = false;
        } catch (Exception e) {
            processing = false;
        }
    }
}