DatagramChannel是nio中处理UDP的类,可以使用2种方式:
DatagramChannel.receive(ByteBuffer dst)和DatagramChannel.send(ByteBuffer src, SocketAddress target)
调用connect()之后,使用read和write.
方式一
send和receive示例
/**
* @author cxg
*
*/
public class DatagramChannelSender {
public static void main(String[] args) {
try {
send();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void send() throws IOException{
DatagramChannel channel =DatagramChannel.open();
ByteBuffer buffer =ByteBuffer.wrap("下雨的夜晚很安静".getBytes("utf-8"));
channel.send(buffer, new InetSocketAddress("localhost",10022));
channel.close();
}
}
/**
* @author cxg
*
*/
public class DatagramChannelReveiver {
public static void main(String[] args) {
try {
receive();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void receive() throws IOException{
DatagramChannel channel =DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(10022));
ByteBuffer buffer =ByteBuffer.allocate(60);
while(channel.receive(buffer)==null){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
buffer.flip();
String recStr =Charset.forName("utf-8").newDecoder().decode(buffer).toString();
System.out.println(recStr);
channel.close();
}
}
方式2
connect()说明
1.只起到,限制数据包的接收和发送来源
2.不会阻塞
3.使用read和write的必要条件,否则抛出"NotYetConnectedException "
其他注意
DatagramChannel不能注册SelectionKey.OP_CONNECT
数据包的最大容量是65507字节