加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 19:31:56 所属栏目:Java 来源:网络整理
导读:使用SocketChannel sc =(SocketChannel)key.channel();,我们可以从端口获取数据到缓冲区. 为了从端口连续接收数据而不会丢失数据,代码应如何? 这是我的代码 import java.io.*;import java.net.*;import java.nio.*;import java.nio.channels.*;import 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 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,n );
                            System.out.println(new String(array,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 );
  }
}
最佳答案
您可以读取的最大大小实际上受到内存容量的限制.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读