码迷,mamicode.com
首页 > 编程语言 > 详细

Java-NIO(八):DatagramChannel

时间:2017-07-31 23:58:22      阅读:344      评论:0      收藏:0      [点我收藏+]

标签:address   pen   cti   conf   ddr   非阻塞   udp   cat   array   

Java NIO中的DatagramChannel是一个能收发UDP包的通道。
操作步骤:
  1)打开 DatagramChannel
  2)接收/发送数据

同样它也支持NIO的非阻塞模式操作,例如:

 1 @Test
 2     public void send() throws IOException {
 3         DatagramChannel channel = DatagramChannel.open();
 4         channel.configureBlocking(false);
 5 
 6         ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
 7 
 8         Scanner scanner = new Scanner(System.in);
 9         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
10         while (scanner.hasNext()) {
11             String line = scanner.next();
12             byteBuffer.put((format.format(new Date()) + ":" + line).getBytes());
13             byteBuffer.flip();
14 
15             channel.send(byteBuffer, new InetSocketAddress("127.0.0.1", 9899));
16             byteBuffer.clear();
17         }
18 
19         channel.close();
20     }
21 
22     @Test
23     public void receive() throws IOException {
24         DatagramChannel channel = DatagramChannel.open();
25         channel.configureBlocking(false);
26         channel.bind(new InetSocketAddress(9899));
27 
28         Selector selector = Selector.open();
29         channel.register(selector, SelectionKey.OP_READ);
30 
31         while (selector.select() > 0) {
32             Iterator<SelectionKey> selectionKeys = selector.selectedKeys().iterator();
33             while (selectionKeys.hasNext()) {
34                 SelectionKey selectionKey = selectionKeys.next();
35                 if (selectionKey.isReadable()) {
36                     ByteBuffer buffer = ByteBuffer.allocate(1024);
37                     channel.receive(buffer);
38                     buffer.flip();
39                     System.out.println(new String(buffer.array(), 0, buffer.limit()));
40                     buffer.clear();
41                 }
42 
43                 selectionKeys.remove();
44             }
45         }
46 
47     }

 

Java-NIO(八):DatagramChannel

标签:address   pen   cti   conf   ddr   非阻塞   udp   cat   array   

原文地址:http://www.cnblogs.com/yy3b2007com/p/7266313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!