2
我在做一個客戶端服務器。我已經知道服務器可以發送硬編碼文件,但不是指定的客戶端。我將不得不發送文本文件。據我瞭解:客戶端首先發送文件名,然後,服務器發送它,沒有什麼複雜的,但我得到各種錯誤,這段代碼得到一個連接重置/套接字關閉錯誤。主要的問題是,沒有太多時間研究網絡。Java請求文件,發送文件(客戶端服務器)
我很感激任何幫助,我可以得到。
編輯。 我發現了一個解決辦法,關閉一個流導致套接字關閉,爲什麼?它不應該發生,應該嗎?
服務器端:
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();
您在閱讀之前是否嘗試過使用System.out.println(sdata.available())?也許沒有什麼可讀的。 –
該代碼沒有運行那麼遠檢查:/ – MustSeeMelons
但它是否到達位置= sdata.readUTF(),你說連接重置?我的意思是在那之前。 –