首页 > 编程语言 > 详细

java的NIO之UDP用法

时间:2014-09-25 16:35:58      阅读:358      评论:0      收藏:0      [点我收藏+]

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));

	}

}


输出结果

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


java的NIO之UDP用法

原文:http://blog.csdn.net/itbuluoge/article/details/39552397

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!