博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
10、NIO--DategramChannel
阅读量:6962 次
发布时间:2019-06-27

本文共 1466 字,大约阅读时间需要 4 分钟。

 

 

 

DatagramChannel

 Java NIO中的DatagramChannel是一个能收发

  UDP包的通道。
 操作步骤:
  打开 DatagramChannel
  接收/发送数据

 

 

服务端

@Test    public void receive() throws IOException{        DatagramChannel dc = DatagramChannel.open();                dc.configureBlocking(false);                dc.bind(new InetSocketAddress(8082));                //选择器        Selector selector = Selector.open();                dc.register(selector, SelectionKey.OP_READ);                while(selector.select() > 0){            Iterator
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())); } } it.remove(); } }

 

客户端:

@Test    public void send() throws IOException{                DatagramChannel dc = DatagramChannel.open();                dc.configureBlocking(false);                ByteBuffer buf = ByteBuffer.allocate(1024);                buf.put("MeChengs".getBytes());        buf.flip();        dc.send(buf, new InetSocketAddress("127.0.0.1", 8082));                dc.close();    }

 

 

转载于:https://www.cnblogs.com/Mrchengs/p/10840845.html

你可能感兴趣的文章
How processor, assembler, and programming langu...
查看>>
五种方法解决Magento中jQuery和Prototype兼容性
查看>>
PPT模板网站
查看>>
InSave 隐私政策
查看>>
[Linux command]批处理注释
查看>>
delphi 操作文件时间的函数
查看>>
nodjs 生产环境及升级问题
查看>>
JS判断客户端是否是iOS或者Android手机移动端
查看>>
Swing控件
查看>>
快速JavaEE轻量级框架&公用业务模块 设计&实现 6.1 - DAO测试
查看>>
文本特征提取算法实现
查看>>
这个qq的域名【c.gj.qq.com】是做什么的?chrome浏览器,访问什么网站都有这个请求...
查看>>
C++中的类型转换
查看>>
大数据引发的变革与企业面临的挑战
查看>>
HttpServlet详解
查看>>
无线网络
查看>>
架构设计:生产者/消费者模式 第4页:注意事项
查看>>
1233
查看>>
php写入文件权限失败 file_put_contents: failed to open stream: Permission denied
查看>>
MarMoible的 java4android视频
查看>>