0

こんにちは、私は 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();           
    }
}
4

1 に答える 1

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ストリームを使用すると、すべてがはるかに簡単になります。

于 2012-10-24T23:20:16.993 に答える