DatagramChannel使用

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字节


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值