NIO实现UDP数据传输

最近用NIO写了一个UDP传输,服务器和客户端都存在,测试了并发数至少1000

NIO写UDP----server
用NIO写UDP
/serverTest.java
import java.io.*;
import java.net.*;
import java.nio.*;
import java.lang.*;
import java.nio.channels.*;
import java.util.*;
import test.control.ConnProtocol;
import test.util.Constant;

public class ServerTest implements Runnable
{
  private int port;
  public ServerTest( int port ) {
    this.port = port;
    new Thread( this ).start();
  }

  public void run() {
    try {
      //建立
      DatagramChannel dc = DatagramChannel.open();
      dc.configureBlocking( false ) ;

      SocketAddress address = new InetSocketAddress(port ) ;
      //本地绑定端口
      DatagramSocket ds = dc.socket() ;
      ds.setReceiveBufferSize(20480);
      ds.bind( address ) ;

      //注册
      Selector select = Selector.open() ;
      dc.register( select , SelectionKey.OP_READ ) ;
      System.out.println( "Listening on port "+port );

      ByteBuffer buffer = ByteBuffer.allocateDirect( Constant.BUFFERSIZE ) ;

      int number = 0;  //只为记录接受的字节数
      while(true){
        int num = select.select() ;
        //如果选择器数目为0,则结束循环
        if (num == 0) {
          continue;
        }
        //得到选择键列表
        Set Keys = select.selectedKeys() ;
        Iterator it = Keys.iterator() ;

        while( it.hasNext() ){
          SelectionKey k = ( SelectionKey )it.next() ;
          if( ( k.readyOps() & SelectionKey.OP_READ )
              == SelectionKey.OP_READ ){

            DatagramChannel cc = ( DatagramChannel )k.channel() ;
            //非阻塞
            cc.configureBlocking(false);

            //接收数据并读到buffer中
            buffer.clear();
            SocketAddress client = cc.receive( buffer ) ;

            buffer.flip();
            if(buffer.remaining()<=0)
            {System.out.println("bb is null");}
            //记录接收到的字节总数
            number += buffer.remaining();
            byte b[] =new byte[buffer.remaining()];
            for(int i =0;i<buffer.remaining();i++) {
              b[i] = buffer.get(i);
            }
            String in = new String(b,"gb2312");
            System.out.println("number::::"+number);
            //执行操作,并回发送
                //……省略……
          }
        }
        Keys.clear();
      }

    } catch( IOException ie ) {
      System.err.println( ie );
    }
  }

  static public void main( String args[] ) throw* **ception {
    int port = 1111;//Integer.parseInt( args[0] );

    new ServerTest( port );
  }
}

/NIO写UDP----client
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class ClientTest extends Thread{
  private String host;
  private int port;
  int j = 0;
  int number;
  public ClientTest( String host, int port, int numThreads ) {
    this.host = host;
    this.port = port;

    for (int i=0; i<numThreads; ++i) {
      new Thread( this ).start();
/*
      try
      {
        sleep(100);
      }
      catch (Exception e)
      {

      }
*/
    }
  }
  public void run(){
      //构造一个数据报Socket
    DatagramChannel dc = null;
         try {
      dc = DatagramChannel.open();
         }
         catch (IOException ex4) {
         }
    SocketAddress address = new InetSocketAddress(host, port);
    try {
      dc.connect(address);
    }
    catch (IOException ex) {
    }
    //dc = Socket.getChannel();
    //发送请求
    ByteBuffer bb = ByteBuffer.allocate(130);

    byte[] b = new byte[130];
    String s = "sdfas";

    s = "sss";

     b = s.getBytes();
      bb.clear();
      bb.put(b);
      bb.flip();
      //测试
      if(bb.remaining()<=0)
      {System.out.println("bb is null");}
  //while(true) {
    try {
      int num = dc.send(bb,address);
      number = number + num;

      System.out.println("number:::"+number);


      bb.clear();
      dc.receive(bb);
      bb.flip();
      byte [] by = new byte[bb.remaining()];
      for(int i=0 ;i<bb.remaining();i++ ){
        by[i] = bb.get(i);
      }
      String ss = new String(by,"gb2312");
      System.out.println(ss);
    }
    catch (Exception ex1) {
    }
  //}
  }

  //start
  public static void main(String[] args) {
    String host = "127.0.0.1";//args[0];
    int port = 1111;//Integer.parseInt( args[1] );
    int numThreads = 3;//Integer.parseInt( args[2] );

    new ClientTest( host, port, numThreads );
  }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值