簡體   English   中英

Java請求文件,發送文件(客戶端服務器)

[英]Java request file, send file (Client-server)

我正在做一個客戶端服務器。 我已經了解到服務器可以發送硬編碼文件,但不能指定客戶端。 我將只發送文本文件。 據我了解:客戶端首先發送文件名,然后服務器發送文件名,沒有什么復雜的,但是我遇到了各種各樣的錯誤,此代碼是連接重置/套接字關閉錯誤。 主要問題是,沒有太多時間來研究網絡。

我會很感激我能得到的任何幫助。

編輯。 我找到了解決方法,關閉流會導致套接字關閉,為什么? 它不應該發生,對嗎?

服務器端:

    InputStream sin=newCon.getInputStream();
    DataInputStream sdata=new DataInputStream(sin);
    location=sdata.readUTF();   
    //sdata.close();
    //sin.close();

File toSend=new File(location);
byte[] array=new byte[(int)toSend.length()];
FileInputStream fromFile=new FileInputStream(toSend);
BufferedInputStream toBuffer=new BufferedInputStream(fromFile);
toBuffer.read(array,0,array.length);

OutputStream out=newCon.getOutputStream(); //Socket-closed...
out.write(array,0,array.length);
out.flush();
toBuffer.close();
newCon.close();

客戶端:

int bytesRead;
server=new Socket(host,port);

OutputStream sout=server.getOutputStream();
DataOutputStream sdata=new DataOutputStream(sout);
sdata.writeUTF(interestFile);
//sdata.close();
//sout.close();

InputStream in=server.getInputStream();     //socket closed..
OutputStream out=new FileOutputStream("data.txt");
byte[] buffer=new byte[1024];
while((bytesRead=in.read(buffer))!=-1)
{
    out.write(buffer,0,bytesRead);
}
out.close();
server.close();

在寫入客戶端輸出流時,嘗試從服務器中分塊讀取文件,而不是創建臨時字節數組並將整個文件讀入內存。 如果請求的文件很大怎么辦? 還要在finally塊中在服務器端關閉新的Socket,以便即使拋出異常也關閉套接字。

服務器端:

    Socket newCon = ss.accept();
    FileInputStream is = null;
    OutputStream out = null;
    try {
        InputStream sin = newCon.getInputStream();
        DataInputStream sdata = new DataInputStream(sin);
        String location = sdata.readUTF();
        System.out.println("location=" + location);
        File toSend = new File(location);
        // TODO: validate file is safe to access here
        if (!toSend.exists()) {
            System.out.println("File does not exist");
            return;
        }
        is = new FileInputStream(toSend);
        out = newCon.getOutputStream();
        int bytesRead;
        byte[] buffer = new byte[4096];
        while ((bytesRead = is.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
        out.flush();
    } finally {
        if (out != null)
            try {
               out.close();
            } catch(IOException e) {
            }
        if (is != null)
            try {
               is.close();
            } catch(IOException e) {
            }
        newCon.close();
    }

如果使用Apache Common IOUtils庫,則可以減少許多代碼來將文件讀/寫到流。 在這里5線下降到1線。

org.apache.commons.io.IOUtils.copy(is, out);

請注意,擁有通過絕對路徑到遠程客戶端的文件來提供文件的服務器是潛在的危險,目標文件應限於給定的目錄和/或文件類型集。 不想將系統級文件提供給未經身份驗證的客戶端。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM