`
QING____
  • 浏览: 2231912 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

NIO部分:DatagramChannel实例

 
阅读更多
package com.test.socket;

import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.charset.Charset;
import java.util.Iterator;

public class DatagramChannelTestMain {
	private static final int port = 30008;
	private static final int TIMEOUT = 3000;

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Thread serverThread = new ServerThread();
		serverThread.start();
		Thread clientThread = new ClientThread();
		clientThread.start();
		Thread.sleep(2000);
	}

	static class ServerThread extends Thread {

		@Override
		public void run() {
			DatagramChannel channel = null;
			try {
				channel = DatagramChannel.open();
				channel.configureBlocking(false);
				DatagramSocket socket = channel.socket();
				socket.bind(new InetSocketAddress(port));
				Selector selector = Selector.open();
				channel.register(selector, SelectionKey.OP_READ);
				while(selector.isOpen()){
					System.out.println("S....!!!");
					if(selector.select() == 0){//select must be
						System.out.println("s....");
						Thread.sleep(2000);
						continue;
					}
					Iterator<SelectionKey> it = selector.selectedKeys().iterator();
					while(it.hasNext()){
						SelectionKey key = it.next();
						if(key.isValid() && key.isReadable()){
							read(key);
						}
					}
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				if(channel != null){
					try{
						channel.close();
					}catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}
		}

		private void read(SelectionKey key) throws Exception {
			DatagramChannel channel = (DatagramChannel)key.channel();
			System.out.println("channel" + channel.toString());
			ByteBuffer byteBuffer = ByteBuffer.allocate(256);
			InetSocketAddress address = (InetSocketAddress)channel.receive(byteBuffer);
			if(address == null){
				System.out.println(".....");
			}else{
				System.out.println(address.getAddress() + "//" + address.getPort());
			}
			byteBuffer.flip();
			Charset charset = Charset.defaultCharset();
			CharBuffer charBuffer = charset.decode(byteBuffer);
			System.out.println("Server read:" + charBuffer.toString());
			//if write,please here.
			byteBuffer = charset.encode("this is server sent!");
			channel.send(byteBuffer, address);
			key.interestOps(SelectionKey.OP_READ);
		}

	}

	static class ClientThread extends Thread {
		@Override
		public void run() {
			DatagramChannel channel = null;
			try {
				channel = DatagramChannel.open();
				channel.configureBlocking(false);
				channel.connect(new InetSocketAddress("10.12.124.19",port));
				while(!channel.isConnected()){
					System.out.println("....");
				}
				Selector selector = Selector.open();
				channel.register(selector, SelectionKey.OP_WRITE);
				while(selector.isOpen()){
					if(selector.select() == 0){
						Thread.sleep(2000);
						continue;
					}
					Iterator<SelectionKey> it = selector.selectedKeys().iterator();
					while(it.hasNext()){
						SelectionKey key = it.next();
						if(key.isValid() && key.isWritable()){
							write(key);
						}else if(key.isReadable()){
							read(key);
						}
					}
				}
			}catch (Exception e) {
				e.printStackTrace();
			}finally{
				if(channel != null){
					try{
						channel.close();
					}catch(Exception ex){
						ex.printStackTrace();
					}
				}
			}
		}
		
		private void write(SelectionKey key) throws Exception{
			DatagramChannel channel = (DatagramChannel)key.channel();
			Charset charset = Charset.defaultCharset();
			ByteBuffer byteBuffer = charset.encode("this is client sent!");
			System.out.println("p:" + byteBuffer.position() + "//l:" + byteBuffer.limit());
			while(byteBuffer.hasRemaining()){
				channel.write(byteBuffer);
			}
			System.out.println("cw ok!");
			key.interestOps(SelectionKey.OP_READ);
		}
		
		private void read(SelectionKey key) throws Exception{
			DatagramChannel channel = (DatagramChannel)key.channel();
			Charset charset = Charset.defaultCharset();
//			ByteBuffer byteBuffer = charset.encode("this is client sent!");
//			System.out.println("p:" + byteBuffer.position() + "//l:" + byteBuffer.limit());
			ByteBuffer byteBuffer = ByteBuffer.allocate(256);
			while(channel.read(byteBuffer) > 0){
				//
			}
			byteBuffer.flip();
			CharBuffer charBuffer = charset.decode(byteBuffer);
			System.out.println("Client read:" + charBuffer.toString());
			key.interestOps(SelectionKey.OP_WRITE);
		}
	}
}

 

分享到:
评论

相关推荐

    Nio详细介绍,实例演示

    Nio详细介绍,实例演示 Nio详细介绍,实例演示 Nio详细介绍,实例演示Nio详细介绍,实例演示 Nio详细介绍,实例演示 Nio详细介绍,实例演示

    postgres-nio::elephant:用于PostgreSQL非阻塞,事件驱动的Swift客户端

    postgres-nio::elephant:用于PostgreSQL非阻塞,事件驱动的Swift客户端

    NIO编程实现实例

    NIO编程实现实例,

    httpcore-nio-4.4.6-API文档-中英对照版.zip

    Maven坐标:org.apache.httpcomponents:httpcore-nio:4.4.6; 标签:apache、httpcomponents、nio、httpcore、jar包、java、中英对照文档; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可...

    JAVA-NIO程序设计完整实例

    NULL 博文链接:https://shift-alt-ctrl.iteye.com/blog/1840554

    一站式学习Java网络编程 全面理解BIO:NIO:AIO1

    一站式学习Java网络编程 全面理解BIO:NIO:AIO1

    java NIO推送实例

    java NIO 消息推送实例代码,解压Tmp.zip Desk为桌面程序,DeskAppServer为服务端程序,江巅

    java-nio.rar_java nio_nio 对象实例化

    实例化HashMap类型的一个对象用来存放每一个客户对应的套接字和通道,实例化线程通道选择器等,当由用户请求时,接受,加入选择项,注册感兴趣事件,另一线程处理输入流,在前面加echo:,发给客户端。

    nio4r:适用于可扩展网络客户端和服务器的跨平台异步IO原语

    Ruby的新I / O(nio4r) :可伸缩网络客户端和服务器的跨平台异步I / O原语。 根据Java NIO API建模,但为易于使用而进行了简化。 nio4r为Ruby提供了一个抽象的,跨平台的有状态I / O选择器API。 I / O选择器是基于...

    Java NIO实例

    nio代码实例,Java NIO 系列教程,买不了吃亏,买不了上当

    nio2:java.nio.file 包周围的 clojure 包装器

    java.nio.file包的轻量级包装器。 使用 与莱恩: [nio2 " 0.2.1 " ] 动机 创建这个库有两个主要原因: 允许 clojure 开发人员利用 NIO2 功能 使文件系统 IO 在 clojure 中可测试 引入了与文件系统进行惰性交互的...

    socket通信NIO代理模式demo实例

    socket通信nio模式有很多实现方式,但是在性能上、资源上一般很少考虑,这里封装了一个性能极强的程序。

    httpcore-nio-4.4.14-API文档-中文版.zip

    Maven坐标:org.apache.httpcomponents:httpcore-nio:4.4.14; 标签:apache、httpcomponents、httpcore、nio、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览...

    xnio-nio-3.8.4.Final-API文档-中文版.zip

    Maven坐标:org.jboss.xnio:xnio-nio:3.8.4.Final; 标签:jboss、xnio、nio、jar包、java、中文文档; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的...

    多线程NIO客户端实例

    多线程NIO客户端实例

    NIO.rar_NIO_java nio

    nio 的实现例子 里面有详细的中文注释 配合查询api 帮助你更好地学习nio 特点:非阻塞

    java NIO 视频教程

    Java NIO: Channels and Buffers(通道和缓冲区) 标准的IO基于字节流和字符流进行操作的,而NIO是基于通道(Channel)和缓冲区(Buffer)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。 ...

    JavaNIO chm帮助文档

    Java NIO系列教程(一) Java NIO 概述 Java NIO系列教程(二) Channel ...Java NIO系列教程(十) Java NIO DatagramChannel Java NIO系列教程(十一) Pipe Java NIO系列教程(十二) Java NIO与IO

    手写 tomcat nio

    手写 tomcat nio http://knight-black-bob.iteye.com/blog/2408450

    nioreactor:无阻塞IOReact器

    由于React堆线程可以在执行IO时饱和,因此nioreactor使用接受器线程将新连接转发到可以在非阻塞模式下处理读取和写入的React堆池。 建筑分布 要求 2.2.0或以上 Java 8或以上 建立: git clone mvn clean install ...

Global site tag (gtag.js) - Google Analytics