2011-06-21 100 views
-1

我想創建小型客戶端服務器TCP文件傳輸程序。我有一件事情有問題。當我從客戶端發送文件到服務器時,例如txt文件:omg.txt,我希望服務器讀取傳入的文件名。Java TCP服務器讀取文件名

所以 - 客戶端發送omg.txt,服務器說「新文件recived:omg.txt」。我試圖使用BufferedReader(服務器)和DataOutputStream(客戶端,因爲你必須寫文件的名稱發送它),但它沒有工作。

編輯:

客戶:

Socket sock = new Socket("localhost",13267); 
System.out.println("Wait..."); 
Scanner input = new Scanner(System.in); 

while(true){ 
// wysylanie 
System.out.println("Filename"); 
String p = input.nextLine(); 
File myFile = new File (p); 
boolean exists = (new File(p)).exists(); 
if (exists) { 
     byte [] mybytearray = new byte [(int)myFile.length()]; 
     FileInputStream fis = new FileInputStream(myFile); 
     BufferedInputStream bis = new BufferedInputStream(fis); 
     BufferedOutputStream out = new BufferedOutputStream(sock.getOutputStream()); 
     bis.read(mybytearray,0,mybytearray.length); 
     OutputStream os = sock.getOutputStream(); 
     System.out.println("Wait..."); 
     os.write(mybytearray,0,mybytearray.length); 
     os.flush(); 
     System.out.println("Done"); 
     sock.close(); 
    } 

服務器:

int filesize=6022386; 
int bytesRead; 
int current = 0; 

ServerSocket servsock = new ServerSocket(13267); 
Scanner input = new Scanner(System.in); 


while (true) { 
System.out.println("Wait..."); 
Socket sock = servsock.accept(); 
System.out.println("OK : " + sock); 

// odbior pliku 
byte [] mybytearray = new byte [filesize]; 
InputStream is = sock.getInputStream(); 
bytesRead = is.read(mybytearray,0,mybytearray.length); 
current = bytesRead; 
do { 
    bytesRead = 
     is.read(mybytearray, current, (mybytearray.length-current)); 
    if(bytesRead >= 0) current += bytesRead; 
} while(bytesRead > -1); 

System.out.println("New filename"); 
String p = input.nextLine(); 
File plik = new File(p); 
FileOutputStream fos = new FileOutputStream(plik); 
BufferedOutputStream bos = new BufferedOutputStream(fos); 
bos.write(mybytearray, 0 , current); 
bos.flush(); 

System.out.println("File saved"); 
bos.close(); 
sock.close(); 

我試圖做這樣的事情:

客戶端插件:

DataOutputStream outToServer = new DataOutputStream(sock.getOutputStream()); 

sentence = input.nextLine(); 
outToServer.writeBytes(sentence); 

服務器插件:

BufferedReader inFromClient = new BufferedReader(new InputStreamReader(sock.getInputStream())); 

clientSentence = inFromClient.readLine(); 
System.out.println(clientSentence); 

...但偏偏我已經 「等等。」 所有的時間爲客戶

+0

到底是什麼問題了嗎?文件名實際上是否完全轉移到服務器上? – miku

回答

2

TCP傳輸只是原始數據。如果您想發送帶有文件名的文件,您可能需要使用更高級別的協議,例如FTP或TFTP。

如果你真的想使用純TCP,你需要以某種方式在你的消息中編碼文件名。例如,您可以將文件名作爲消息的第一行發送,然後讓另一端將其餘消息轉換爲具有該名稱的文件。

這可能對你有幫助:http://www.adp-gmbh.ch/blog/2004/november/15.html

+1

+1,我想補充一點,如果你把它作爲一個愛好項目來娛樂自己,那麼一定要繼續。但是如果你想在生產環境中部署它,請不要這樣做。網絡文件傳輸存在太多安全問題,並且有許多解決這些問題的現成解決方案。 – biziclop