簡體   English   中英

NIO服務器/客戶端發送映像問題

[英]NIO Server/Client sending image problems

大家好,我一直在嘗試制作NIO服務器/客戶端程序。 我的問題是服務器僅發送14個字節,然后將不再發送任何內容。 我已經坐了這么長時間,以至於我真的再也看不到任何東西,因此決定看看這里是否有人可以看到問題

服務器代碼:

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();           
    }
}
  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流將更加簡單。

暫無
暫無

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

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