可使用Java中Nio包的socketChannel从客户端套接字获取的最大数据大小

使用SocketChannel sc =(SocketChannel)key.channel();,我们可以从端口获取数据到缓冲区.
为了从端口连续接收数据而不会丢失数据,代码应如何?

 

这是我的代码

 

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;

public class MultiPortEcho
{
  private int ports[];
  private ByteBuffer echoBuffer = ByteBuffer.allocate(32000);

  public MultiPortEcho( int ports[] ) throws IOException
  {
    this.ports = ports;
    go();
  }

  private void go() throws IOException
  {
    // Create a new selector
    Selector selector = Selector.open();

    // Open a listener on each port, and register each one
    // with the selector
    for (int i=0; i 2)
                                System.out.print(ss.substring(6) + " ");
                            else System.out.print(ss + " ");
                        }
                      break;
                    }

                    echoBuffer.flip();

                    sc.write( echoBuffer );
                    bytesEchoed += r;*/
              }

             //System.out.println( "Echoed "+bytesEchoed+" from "+sc );
             //it.remove();
        }

      }

//System.out.println( "going to clear" );
//      selectedKeys.clear();
//System.out.println( "cleared" );
    }
  }

  static public void main( String args[] ) throws Exception
  {
    FileOutputStream fileoutputstream = new FileOutputStream("MultiPort.txt", false);
    PrintStream printstream = new PrintStream(fileoutputstream);
    System.setOut(printstream);
    if (args.length<=0) {
      System.err.println( "Usage: java MultiPortEcho port [port port ...]" );
      System.exit( 1 );
    }

    int ports[] = new int[args.length];

    for (int i=0; i

最佳答案

您可以读取的最大大小实际上受到内存容量的限制.

 

但是,您无需读取超大块即可提高效率.您应该发现1 MB绰绰有余.实际上,您可能会发现4KB的块足够大,可以为1 Gb连接获得最大带宽.

你可能感兴趣的:(可使用Java中Nio包的socketChannel从客户端套接字获取的最大数据大小)