Java NIO中的DatagramChannel是一个能收发UDP包的通道。由于UDP是无链接的网络协议,因此不能像其它通道那样读取和写入。它发送和接收的是数据包。服务器
打开 DatagramChannel
下面是 DatagramChannel 的打开方式:网络
DatagramChannel channel = DatagramChannel.open(); channel.socket().bind(new InetSocketAddress(9999));
这个例子打开的 DatagramChannel能够在UDP端口9999上接收数据包。socket
接收数据
经过receive()方法从DatagramChannel接收数据,如:code
ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); channel.receive(buf);
receive()方法会将接收到的数据包内容复制到指定的Buffer. 若是Buffer容不下收到的数据,多出的数据将被丢弃。ip
发送数据
经过send()方法从DatagramChannel发送数据,如:get
String newData = "New String to write to file..." + System.currentTimeMillis(); ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(newData.getBytes()); buf.flip(); int bytesSent = channel.send(buf, new InetSocketAddress("jenkov.com", 80));
这个例子发送一串字符到”jenkov.com”服务器的UDP端口80。 由于服务端并无监控这个端口,因此什么也不会发生。也不会通知你发出的数据包是否已收到,由于UDP在数据传送方面没有任何保证。it
链接到特定的地址
能够将DatagramChannel“链接”到网络中的特定地址的。因为UDP是无链接的,链接到特定地址并不会像TCP通道那样建立一个真正的链接。而是锁住DatagramChannel ,让其只能从特定地址收发数据。监控
这里有个例子:
channel.connect(new InetSocketAddress("jenkov.com", 80));
当链接后,也能够使用read()和write()方法,就像在用传统的通道同样。只是在数据传送方面没有任何保证。这里有几个例子:file
int bytesRead = channel.read(buf); int bytesWritten = channel.write(but);