2012-10-24 58 views
0

嗨,我一直在努力製作NIO服務器/客戶端程序。 我的問題是,服務器只發送14個字節,那麼它不會再發送任何東西。我坐在這,我真的什麼都看不到了,併爲此這麼久決定,看是否有人在這裏可以看到問題NIO服務器/客戶端發送圖像問題

服務器代碼:

import java.nio.*; 
import java.nio.channels.*; 
import java.nio.charset.*; 

public class Testserver { 
    public static void main(String[] args) throws java.io.IOException { 

     ServerSocketChannel server = ServerSocketChannel.open(); 
     server.socket().bind(new java.net.InetSocketAddress(8888)); 

     for(;;) { 
      // Wait for a client to connect 
      SocketChannel client = server.accept(); 

      String file = ("C:\\ftp\\pic.png"); 


      ByteBuffer buf = ByteBuffer.allocate(1024); 
      while(client.read(buf) != -1){ 

      buf.clear(); 
      buf.put(file.getBytes()); 
      buf.flip(); 

      client.write(buf); 
      // Disconnect from the client 
      } 
      client.close(); 
     } 
    } 
} 

客戶:

import java.io.IOException; 
import java.net.InetSocketAddress; 
import java.nio.ByteBuffer; 
import java.nio.channels.Channels; 
import java.nio.channels.ReadableByteChannel; 
import java.nio.channels.SocketChannel; 
import java.nio.channels.WritableByteChannel; 
import java.io.*; 
import java.net.*; 
import java.nio.*; 
import java.nio.channels.*; 
import java.nio.charset.*; 
public class Testclient { 

    public static void main(String[] args) throws IOException { 



     SocketChannel socket = SocketChannel.open(new InetSocketAddress(8888)); 



     FileOutputStream out = new FileOutputStream("C:\\taemot\\picNIO.png"); 
     FileChannel file = out.getChannel(); 

     ByteBuffer buffer = ByteBuffer.allocateDirect(8192); 

     while(socket.read(buffer) != -1) { 
      buffer.flip();  
      file.write(buffer); 
      buffer.compact();  
      buffer.clear(); 
     } 
     socket.close();   
     file.close();   
     out.close();   
    } 
} 

回答

0
  1. 您只發送文件名,而不是文件內容。文件名是14個字節。

  2. 每次客戶端發送任何東西時,都會發送該消息。然而,客戶端從不發送任何東西,所以我很驚訝你甚至得到了14個字節。

  3. 你忽略了write()的結果。

如果要發送文件內容,請使用FileChannel打開它。同樣,用FileChannel打開客戶端中的目標文件。然後複製循環在兩個地方是相同的。複製渠道之間的緩衝的正確方法如下:

while (in.read(buffer) >= 0 || buffer.position() > 0) 
{ 
    buffer.flip(); 
    out.write(buffer); 
    buffer.compact(); 
} 

注意,這需要照顧的部分讀取,部分寫入,並最終寫入讀取EOS之後。

說了這麼多,我根本沒有看到任何理由在這裏使用NIO。使用java.net套接字和java.io流將會更簡單。