java的NIO之UDP用法

来源:互联网 发布:淘宝十字绣成品 编辑:程序博客网 时间:2024/05/16 10:52

Java NIO中的DatagramChannel是一个能收发UDP包的通道。因为UDP是无连接的网络协议,所以不能像其它通道那样读取和写入。它发送和接收的是数据包。

服务器端代码

package com.test.nio;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.DatagramChannel;public class TestUDPServer {/** * @param args * @throws Exception  */public static void main(String[] args) throws Exception {DatagramChannel channel=DatagramChannel.open();channel.socket().bind(new InetSocketAddress(9999));ByteBuffer buf=ByteBuffer.allocate(48);buf.clear();/*阻塞,等待发来的数据*/channel.receive(buf);/*设置缓冲区可读*/buf.flip();/*循环读出所有字符*/while(buf.hasRemaining()){System.out.print((char)buf.get());}}}
客户端代码

package com.test.nio;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.DatagramChannel;public class TestUDPClient {/** * @param args * @throws Exception  */public static void main(String[] args) throws Exception {DatagramChannel channel=DatagramChannel.open();String newData="hello,itbuluoge!"+System.currentTimeMillis();ByteBuffer buf=ByteBuffer.allocate(48);buf.clear();buf.put(newData.getBytes());buf.flip();/*发送UDP数据包*/int bytesSent=channel.send(buf, new InetSocketAddress("127.0.0.1",9999));}}


输出结果


实际上,上述代码功能非常简单,就是服务器监听,客户端发送一个UDP数据包,如果服务器没有监听或者已经关闭,客户端发送也不会抛出异常,因为UDP就是面向非连接的协议。


0 0
原创粉丝点击