[問題] 傳送檔案寫法的疑問
不好意思小弟又來發問了= =a
先跟上次很用心幫我的人說聲感謝(LaPass和tkcn兩位)
經過了一段時間的奮戰
我的整個程式大致底定
能傳檔案
能看目錄
但是卻有一個我不知道該怎嚜解決的地方
這是Client端實做put的程式碼
String filen = comm.substring(4,comm.length());
System.out.println(filen);
File file = new File(filen);
try
{
FileInputStream fos = new FileInputStream(file);
OutputStream netOut = clientSocket.getOutputStream();
OutputStream doc = new DataOutputStream(new BufferedOutputStream(netOut));
byte[] buf = new byte[2048];
int num = fos.read(buf);
while (num != ( - 1)) //是否讀完文件
{
doc.write(buf, 0, num); //把文件資料寫出網絡緩衝區
doc.flush(); //重整緩衝區把資料寫往客戶端
num = fos.read(buf); //繼續從文件中讀取資料
}
System.out.println("File "+ filen +" has been uploaded to FTPServer "
+ serverAddress);
fos.close();
doc.close();
}catch(Exception e) {
e.printStackTrace();
}
}
以及Server端再Client打put時接收檔案的程式碼
String fileName = get.substring(4,get.length());
String l = inFromClient.readLine();
File file = new File(fileName); //如果文件已經存在,先刪除
if (file.exists()) file.delete();//
int ts = 0;
RandomAccessFile raf = new RandomAccessFile(file, "rw");
InputStream netIn = cs.getInputStream();
InputStream in =new DataInputStream(new BufferedInputStream(netIn)); //
len =Long.parseLong(l) ;
byte[] buf = new byte[2048];
while (true) //是否讀完所有資料
{
int num = 0;
if(in != null)
{
num = in.read(buf);
}
ts += num;
if(ts == num)
{
break;
}
raf.write(buf, 0, num); //將資料寫往文件
}
System.out.println("ftpserver>Client "+ clientAddressString+" has
uploaded the file : " + fileName);
comm = "";//初始化comm使他離開put執行
//in.close();
raf.close();
這是新的Server
但是這樣子變成= =a
完全不會寫入檔案了orz
雖然有跑出那端成功上傳的話
但是實際上全部都卡在getInputStream了
雖然執行上可以讓client再輸入下一個指令
但是輸入第二個指令出現
NumberFormatException:test01put test02.txt
也就是我test01.txt裡的test01沒被丟進文件= =a
反而直接卡住了...
到底錯在哪裡呢ˊˋ
----------------------
基本上兩段程式碼
經過測試
都是能成功傳送檔案無誤
但是問題卻出在最後的close這個東西上...
一但close掉
我要再傳送一次
就會出現socket is close的狀況
但是如果我不關掉
另外一端卻會無法接收結束
一直處於接收中的while迴圈裡出不來
EX:
Clinet輸入put test01.txt
Server接收到test01.txt (確實有傳送成功,因為我有故意加字在裡面去檢查)
Client輸入put test02.txt
跳出錯誤說明寫著Socket is close
不知道要用什麼方法才能在不去close任何socket下
而能讓對面知道已經傳送完成並且結束接收回到等待指令輸入的狀態
有查到說可以試著先送出檔案大小
不過我實作後卻一直跑出啥Native method還啥的= =a
所以想請教眾版友是否知道如何避免使用close這段程式碼
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.57.219.8
→
04/30 22:29, , 1F
04/30 22:29, 1F
→
04/30 22:48, , 2F
04/30 22:48, 2F
→
04/30 22:56, , 3F
04/30 22:56, 3F
→
04/30 23:07, , 4F
04/30 23:07, 4F
推
04/30 23:09, , 5F
04/30 23:09, 5F
→
04/30 23:11, , 6F
04/30 23:11, 6F
→
04/30 23:13, , 7F
04/30 23:13, 7F
→
04/30 23:14, , 8F
04/30 23:14, 8F
→
04/30 23:29, , 9F
04/30 23:29, 9F
※ 編輯: twonia 來自: 61.57.219.8 (05/01 01:49)
→
05/01 01:50, , 10F
05/01 01:50, 10F
→
05/01 01:51, , 11F
05/01 01:51, 11F
→
05/01 09:47, , 12F
05/01 09:47, 12F