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

使用java中nio包的socketChannel可以从客户端套接字获取的最大数据大小,java,Java,使用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 i

使用
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<ports.length; ++i)
    {
      ServerSocketChannel ssc = ServerSocketChannel.open();
      ssc.configureBlocking( false );
      ServerSocket ss = ssc.socket();
      InetSocketAddress address = new InetSocketAddress( ports[i] );
      ss.bind( address );

      SelectionKey key = ssc.register( selector, SelectionKey.OP_ACCEPT );

      System.out.println( "Going to listen on "+ports[i] );
    }

    while (true)
    {
      int num = selector.select();
      System.out.println("num::::"+num);
      Set selectedKeys = selector.selectedKeys();
      Iterator it = selectedKeys.iterator();

      while (it.hasNext())
      {
        SelectionKey key = (SelectionKey)it.next();

        if ((key.readyOps() & SelectionKey.OP_ACCEPT)== SelectionKey.OP_ACCEPT)
          {
              // Accept the new connection
              ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
              SocketChannel sc = ssc.accept();
              sc.configureBlocking( false );

              // Add the new connection to the selector
              SelectionKey newKey = sc.register(selector,SelectionKey.OP_READ);
              it.remove();

              System.out.println( "Got connection from "+sc );
        }
          else if ((key.readyOps() & SelectionKey.OP_READ)== SelectionKey.OP_READ)
          {
              // Read the data
              SocketChannel sc =(SocketChannel)key.channel();
              System.out.println("sc::::"+sc);
              // data to fetched from channel and dump into the datatbase
              int bytesEchoed = 0;
              //while(true)
              {
                    echoBuffer.clear();
                    int r = sc.read(echoBuffer);
                    System.out.println("r:::" + r);
                    /*int pos=echoBuffer.position();
                    System.out.println("pos:::" +pos);*/
                    if (r == -1)
                    {
                        //echoBuffer.flip();
                        echoBuffer.rewind();
                        byte[] array = new byte[100000];
                        while (echoBuffer.hasRemaining())
                        {
                            int n = echoBuffer.remaining();
                            System.out.println("size:" + n);
                            echoBuffer.get(array,0,n );
                            System.out.println(new String(array,0,n));
                            key.cancel();
                            it.remove();

                        }

                    }

                    /*int pos=echoBuffer.position();
                    System.out.println("pos:::" + pos);
                    if(r<=0)
                    {
                        echoBuffer.flip();
                        for (int j = 0; j < pos; j++ )
                        {
                            String ss =Integer.toHexString(echoBuffer.get());
                            if (ss.length() == 1)
                                System.out.print("0" + ss + " ");
                            else if (ss.length() > 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<args.length; ++i) {
      ports[i] = Integer.parseInt( args[i] );
    }

    new MultiPortEcho( ports );
  }
}
import java.io.*;
导入java.net。*;
导入java.nio.*;
导入java.nio.channels.*;
导入java.util.*;
公共类多端口
{
专用int端口[];
私有ByteBuffer echoBuffer=ByteBuffer.allocate(32000);
公共多端口CHO(点端口[])引发IOException
{
这个端口=端口;
go();
}
私有void go()引发IOException
{
//创建一个新的选择器
选择器=选择器。打开();
//在每个端口上打开一个侦听器,并注册每个端口
//用选择器

对于(int i=0;i您可以在这里找到一些线索,其中are
readFromChannel()
函数可能会让您感兴趣

        public void readFromChannel() {
        try {
                   [...]
                   if (readBuffer != null) {
                readBuffer.flip();
                receivingBroker.broker(readBuffer, false);
                if (readBuffer != null) {
                    readBuffer.clear();
                    readBuffer = null;
                }
            }
            if (readBuffer == null || !readBuffer.hasRemaining()) {
                getThread().removeInterestOp(this, SelectionKey.OP_READ);
                getThread().addInterestOp(this, SelectionKey.OP_WRITE);
            }
            if (receivingBroker.isClosed()) {
                if (getChannelListener() != null) {
                    getChannelListener().readFinished(this);
                }
            }
         } catch (Exception e) {
              e.printStackTrace();
         }
         }

对总体设计的评论:

编写网络服务器有两种基本方法。阻塞和非阻塞。2008年,我们的任务是用Python实现一个高性能的网络服务器。在尝试了两种不同的非阻塞方法后,我们发现它更容易使用:

  • 阻塞插座
  • 每个连接一个线程
  • 几个管理器线程
这样,每个线程都可以坐在那里等待数据,直到它死的那一天,当它收到一个完整的数据包时,它就会对数据采取行动


仅供考虑。

作为第一个修复,您应该删除带有key.cancel()的行。保留它将取消密钥,并确保在第一次读取后不会考虑密钥-这将有效地阻止您以后读取任何内容。

当您使用NIO接受连接时,您可以获得套接字并设置相应的输入/输出缓冲区大小

socketChannel.socket().setReceiveBufferSize(512);
socketChannel.socket().setSendBufferSize(16);

由于NIO大量使用操作系统的网络堆栈,这只是一个提示。所有这些事实都在

中有很好的记录。您可以读取的最大大小实际上受到您拥有的内存量的限制


但是,为了提高效率,您不需要读取超大数据块。您应该发现1MB已经足够了。事实上,您可能会发现4KB的数据块足够大,可以为1GB连接获得最大带宽。

大多数操作系统都有缓冲区大小的最小大小,因此设置如此小的值不会达到您认为的效果。我建议gest尝试64*1024或更大。我这样做了,发现它也减少了延迟。(减少了线程之间的传递)