UDP DataGramSocket 小案例

package com.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Date;
import java.util.Iterator;
import java.util.Scanner;

/**
 * UDP  DataGramSocket 小案例
 */
public class TestNonBlockingDatagramChannel {
  @Test
    public void send() throws Exception{
      DatagramChannel dc = DatagramChannel.open();
      dc.configureBlocking(false);
      ByteBuffer buf = ByteBuffer.allocate(1024);//分配缓存区
      Scanner scan = new Scanner(System.in);
      while (scan.hasNext()){
          String str=scan.next();
          buf.put((new Date().toString()+":
"+str).getBytes());
          buf.flip();
          dc.send(buf,new InetSocketAddress("127.0.0.1",9898));
          buf.clear();
      }
      dc.close();
  }
  @Test
  public void receive() throws IOException {
      DatagramChannel dc = DatagramChannel.open();
      dc.configureBlocking(false);
      dc.bind(new InetSocketAddress(9898));
      Selector selector = Selector.open();
      dc.register(selector, SelectionKey.OP_READ);
      while (selector.select()>0){
          Iterator<SelectionKey> it = selector.selectedKeys().iterator();
          while (it.hasNext()){
              SelectionKey sk = it.next();
              if (sk.isReadable()){
                  ByteBuffer buf = ByteBuffer.allocate(1024);
                  dc.receive(buf);
                  buf.flip();
                  System.out.println(new String(buf.array(),0,buf.limit()));
                  buf.clear();
              }
          }
          it.remove();

      }
  }
}

  

先启动服务端,然后再启动客户端,启动成功之后,在客户端中写信息,然后观察服务端的信息,就会发现服务端能够接收到客户端传递过来的信息。

 

原文地址:https://www.cnblogs.com/dongyaotou/p/14423918.html