`
Donald_Draper
  • 浏览: 950756 次
社区版块
存档分类
最新评论

NIO-UDP实例

    博客分类:
  • NIO
nio 
阅读更多
DatagramChannelImpl 解析一(初始化):http://donald-draper.iteye.com/blog/2373245
DatagramChannelImpl 解析二(报文发送与接收):http://donald-draper.iteye.com/blog/2373281
DatagramChannelImpl 解析三(多播):http://donald-draper.iteye.com/blog/2373507
DatagramChannelImpl 解析四(地址绑定,关闭通道等):http://donald-draper.iteye.com/blog/2373519
前面讲过nio tcp通信,今天来看一下udp;
Server-peer
package nio.datagramchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;

/**
 * Sever
 * @author donald
 * 2017年4月11日
 * 下午9:24:03
 */
public class DatagramChannelServer {
	//manager the channel
	private Selector selector;
	/**
	 * stat Server
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException{
		DatagramChannelServer server = new DatagramChannelServer();
		server.initServer("192.168.31.153", 10000);
		server.listen();
	}
	/**
	 * get the ServerSocket and finish some initial work
	 * @param port
	 * @throws IOException
	 */
	public void initServer(String host, int port) throws IOException{
		//get the ServerSocket
		DatagramChannel serverChannel = DatagramChannel.open();
		// set no blocking mode
		serverChannel.configureBlocking(false);
		//bind the port
		serverChannel.socket().bind(new InetSocketAddress(host, port));
		//get the channel manager
		this.selector = Selector.open();
		//Register the channel to manager and bind the event
		serverChannel.register(selector,SelectionKey.OP_READ);
		}
	/**
	 * use asking mode to listen the event of selector
	 * @throws IOException 
	 */
	@SuppressWarnings("rawtypes")
	public void listen() throws IOException{
		System.out.println("=========The Server is start!===========");
		while(true){
			selector.select();
			Iterator ite =  this.selector.selectedKeys().iterator();
			while(ite.hasNext()){
				SelectionKey key = (SelectionKey)ite.next();
				ite.remove();
				if (key.isReadable()) read(key);
			}
			
		}
	}
	/**
	 * deal with the message come from the client
	 * @param key
	 * @throws IOException 
	 */
	public void read(SelectionKey key) throws IOException{
		DatagramChannel channel = (DatagramChannel) key.channel();
		ByteBuffer buf = ByteBuffer.allocate(100);
		//用receive读取数据,如果用read,必须使用connect方法连接Server,并确保建立连接,write一样
		InetSocketAddress socketAddress = (InetSocketAddress) channel.receive(buf); 
		System.out.println("client ip and port:"+socketAddress.getHostString()+","+socketAddress.getPort());
		byte[] data = buf.array();
		String msg = new String(data).trim();
		System.out.println("message come from client:"+msg);
		channel.send(ByteBuffer.wrap(new String("Hello client!").getBytes()),socketAddress);
		channel.close();
	}	
}

Client-peer
package nio.datagramchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;

/**
 * Client
 * @author donald
 * 2017年4月11日
 * 下午9:24:09
 */
public class DatagramChannelClient {
	//manager the channel
	private Selector selector;
	/**
	 * stat Client
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException{
		DatagramChannelClient client = new DatagramChannelClient();
		client.initClient("192.168.31.153",10001);
		client.listen();
	}
	/**
	 * get the Socket and finish some initial work
	 * @param ip Server ip
	 * @param port connect Server port
	 * @throws IOException
	 */
	public void initClient(String ip,int port) throws IOException{
		//get the Socket
		DatagramChannel channel = DatagramChannel.open();
		// set no blocking mode
		channel.configureBlocking(false);
		channel.socket().bind(new InetSocketAddress(ip,port));
		//get the channel manager
		this.selector = Selector.open();
		//Register the channel to manager and bind the event
		channel.register(selector,SelectionKey.OP_READ);
		//发送数据到Server
		channel.send(ByteBuffer.wrap(new String("Hello Server!").getBytes()),new InetSocketAddress("192.168.31.153", 10000));
		}
	/**
	 * use asking mode to listen the event of selector
	 * @throws IOException 
	 */
	@SuppressWarnings("rawtypes")
	public void listen() throws IOException{
		System.out.println("===========The Client is start!===========");
		while(true){
			selector.select();
			Iterator ite =  this.selector.selectedKeys().iterator();
			while(ite.hasNext()){
				SelectionKey key = (SelectionKey)ite.next();
				ite.remove();
				if (key.isReadable()) read(key);
			}
			
		}
	}
	/**
	 * deal with the message come from the server
	 * @param key
	 * @throws IOException 
	 */
	public void read(SelectionKey key) throws IOException{
		DatagramChannel channel = (DatagramChannel) key.channel();
		ByteBuffer buf = ByteBuffer.allocate(100);
		//用receive读取数据,如果用read,必须使用connect方法连接Server,并确保建立连接,write一样
		InetSocketAddress socketAddress = (InetSocketAddress) channel.receive(buf); 
		System.out.println("server ip and port:"+socketAddress.getHostString()+","+socketAddress.getPort());
		byte[] data = buf.array();
		String msg = new String(data).trim();
		System.out.println("message come from server:"+msg);
		channel.close();
	}
	
}

先启动Server-peer,后启动Client-peer,控制台输出:
Server-peer:
=========The Server is start!===========
client ip and port:192.168.31.153,10001
message come from client:Hello Server!

Client-peer:
===========The Client is start!===========
server ip and port:192.168.31.153,10000
message come from server:Hello client!
上面的报文通道使用实例用的是send和receive方法发送和接收报文,是不需要提前建立连接的。
我们看用read和write方法发送和接收报文
Server-peer:
package nio.datagramchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;

/**
 * Sever
 * @author donald
 * 2017年4月11日
 * 下午9:24:03
 */
public class UdpServer {
	//manager the channel
	private Selector selector;
	/**
	 * stat Server
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException{
		UdpServer server = new UdpServer();
		server.initServer("192.168.31.153", 10000);
		server.listen();
	}
	/**
	 * get the ServerSocket and finish some initial work
	 * @param port
	 * @throws IOException
	 */
	public void initServer(String host, int port) throws IOException{
		//get the ServerSocket
		DatagramChannel serverChannel = DatagramChannel.open();
		// set no blocking mode
		serverChannel.configureBlocking(false);
		//bind the port
		serverChannel.socket().bind(new InetSocketAddress(host, port));
		//get the channel manager
		this.selector = Selector.open();
		//Register the channel to manager and bind the event
		serverChannel.register(selector,SelectionKey.OP_READ);
		serverChannel.connect(new InetSocketAddress("192.168.31.153", 10001));
		while(!serverChannel.isConnected()){
			//空转等待连接
		}
	}
	/**
	 * use asking mode to listen the event of selector
	 * @throws IOException 
	 */
	@SuppressWarnings("rawtypes")
	public void listen() throws IOException{
		System.out.println("=========The Server is start!===========");
		while(true){
			selector.select();
			Iterator ite =  this.selector.selectedKeys().iterator();
			while(ite.hasNext()){
				SelectionKey key = (SelectionKey)ite.next();
				ite.remove();
				if (key.isReadable()) read(key);
			}
			
		}
	}
	/**
	 * deal with the message come from the client
	 * @param key
	 * @throws IOException 
	 */
	public void read(SelectionKey key) throws IOException{
		DatagramChannel channel = (DatagramChannel) key.channel();
		System.out.println("is Connected:"+channel.isConnected());
		ByteBuffer buf = ByteBuffer.allocate(100);
		InetSocketAddress socketAddress = (InetSocketAddress) channel.getRemoteAddress(); 
		System.out.println("client ip and port:"+socketAddress.getHostString()+","+socketAddress.getPort());
		channel.read(buf);
		byte[] data = buf.array();
		String msg = new String(data).trim();
		System.out.println("message come from client:"+msg);
		channel.write(ByteBuffer.wrap(new String("Hello client!").getBytes()));
		channel.close();
	}
	
}


Client-peer:
package nio.datagramchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;

/**
 * Client
 * @author donald
 * 2017年4月11日
 * 下午9:24:09
 */
public class UdpClient {
	//manager the channel
	private Selector selector;
	/**
	 * stat Client
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException{
		UdpClient client = new UdpClient();
		client.initClient("192.168.31.153",10001);
		client.listen();
	}
	/**
	 * get the Socket and finish some initial work
	 * @param ip Server ip
	 * @param port connect Server port
	 * @throws IOException
	 */
	public void initClient(String ip,int port) throws IOException{
		//get the Socket
		DatagramChannel channel = DatagramChannel.open();
		// set no blocking mode
		channel.configureBlocking(false);
		channel.socket().bind(new InetSocketAddress(ip,port));
		//get the channel manager
		this.selector = Selector.open();
		//Register the channel to manager and bind the event
		channel.register(selector,SelectionKey.OP_READ);
		channel.connect(new InetSocketAddress("192.168.31.153", 10000));
		while(!channel.isConnected()){
			//空转等待连接
		}
		channel.write(ByteBuffer.wrap(new String("Hello Server!").getBytes()));
		System.out.println("client send message to server is done!");
    }
	/**
	 * use asking mode to listen the event of selector
	 * @throws IOException 
	 */
	@SuppressWarnings("rawtypes")
	public void listen() throws IOException{
		System.out.println("===========The Client is start!===========");
		while(true){
			selector.select();
			Iterator ite =  this.selector.selectedKeys().iterator();
			while(ite.hasNext()){
				SelectionKey key = (SelectionKey)ite.next();
				ite.remove();
				if (key.isReadable()) read(key);
			}
			
		}
	}
	/**
	 * deal with the message come from the server
	 * @param key
	 * @throws IOException 
	 */
	public void read(SelectionKey key) throws IOException{
		DatagramChannel channel = (DatagramChannel) key.channel();
		System.out.println("is Connected:"+channel.isConnected());
		ByteBuffer buf = ByteBuffer.allocate(100);
		InetSocketAddress socketAddress = (InetSocketAddress) channel.getRemoteAddress(); 
		System.out.println("server ip and port:"+socketAddress.getHostString()+","+socketAddress.getPort());
		channel.read(buf); 
		byte[] data = buf.array();
		String msg = new String(data).trim();
		System.out.println("message come from server:"+msg);
		channel.close();
	}
	
}

先启动Server-peer,后启动Client-peer,控制台输出:
Server-peer:
=========The Server is start!===========
is Connected:true
client ip and port:192.168.31.153,10001
message come from client:Hello Server!


Client-peer:
client send message to server is done!
===========The Client is start!===========
is Connected:true
server ip and port:192.168.31.153,10000
message come from server:Hello client!
总结:
send和receive方法发送和接收报文,是不需要提前建立连接的,而read和write方法,
是要建立连接的与SocketChannel相同。建议用send和receive方法发送和接收报文。
0
1
分享到:
评论

相关推荐

    Java NIO实例UDP发送接收数据代码分享

    主要介绍了Java NIO实例UDP发送接收数据代码分享,分享了客户端和服务端完整代码,小编觉得还是挺不错的,共需要的朋友参考。

    Java Socket编程实例(五)- NIO UDP实践

    主要讲解Java Socket编程中NIO UDP的实例,希望能给大家做一个参考。

    netty-demo实例

    也就是说,Netty 是一个基于NIO的客户,服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户,服务端应用。Netty相当简化和流线化了网络应用的编程开发过程,例如,...

    MINA通讯框架的两个简单实例和文档

    它提供了一个抽象的、事件驱动的异步API,使Java NIO在各种传输协议(如TCP/IP,UDP/IP协议等)下快速高效开发。 Apache Mina也称为:  NIO框架  客户端/服务端框架(典型的C/S架构)  网络套接字(networking...

    apache mina socket实例

    mina简单示例,Apache Mina Server 是一个网络通信应用框架,也就是说,它主要是对基于TCP/IP、UDP/IP协议栈的通信框架(当然,也可以提供JAVA 对象的序列化服务、虚拟机管道通信服务等),Mina 可以帮助我们快速...

    java高手真经 光盘源码

    javanio.zip 23.NIO非阻塞通信(Socket/UDP实例、简单聊天系统) javarmi.zip 24.RMI编程(HelloWorld例、计算器实例) javacorba.zip 25.Corba编程(HelloWorld例、计算器实例) 第6部分(4个程序包) java...

    Java高手真经(编程基础卷)光盘全部源码 免积分

    javanio.zip 23.NIO非阻塞通信(Socket/UDP实例、简单聊天系统) javarmi.zip 24.RMI编程(HelloWorld例、计算器实例) javacorba.zip 25.Corba编程(HelloWorld例、计算器实例) 第6部分(4个程序包) java...

    Java高手真经(编程基础卷)光盘全部源码

    javanio.zip 23.NIO非阻塞通信(Socket/UDP实例、简单聊天系统) javarmi.zip 24.RMI编程(HelloWorld例、计算器实例) javacorba.zip 25.Corba编程(HelloWorld例、计算器实例) 第6部分(4个程序包) java...

    JAVA上百实例源码以及开源项目源代码

     基于JAVA的UDP服务器模型源代码,内含UDP服务器端模型和UDP客户端模型两个小程序,向JAVA初学者演示UDP C/S结构的原理。 简单聊天软件CS模式 2个目标文件 一个简单的CS模式的聊天软件,用socket实现,比较简单。 ...

    Mina Tcp实例

    Java NIO开发技术的 TCP/UDP通信协议Mina框架的实例开发,一个简单的小栗子!

    Netty:基于Java NIO的网络服务器Netty生产实例

    Netty作为之前及现在不断学习Netty道路上持续集成项目Netty心跳实现客户端及服务端聊天实现完成Netty回声服务器使用WebSocket实现点对点聊天功能WebSocket实现群聊功能及上下线提醒增加Netty UDP协议实现使用第三方...

    mina实例、资源包、学习文档

    它提供了一个抽象的、事件驱动的异步API,使Java NIO在各种传输协议(如TCP/IP,UDP/IP协议等)下快速高效开发。 Apache Mina也称为:  NIO框架  客户端/服务端框架(典型的C/S架构)  网络套接字(networking...

    JAVA上百实例源码以及开源项目

     基于JAVA的UDP服务器模型源代码,内含UDP服务器端模型和UDP客户端模型两个小程序,向JAVA初学者演示UDP C/S结构的原理。 简单聊天软件CS模式 2个目标文件 一个简单的CS模式的聊天软件,用socket实现,比较简单。 ...

    Apache Mina网络通信应用框架实例

    基于 TCP/IP、UDP/IP协议栈的通信框架 支持串口和虚拟机内部的管道等传输方式 Mina 可以帮助我们快速开发高性能、高扩展性的网络通信应用 Mina 提供了事件驱动、异步操作(JAVA NIO 作为底层支持)的编程模型 本...

    mina2框架+项目实例教程

    它提供了一个抽象的、事件驱动的异步API,使Java NIO在各种传输协议(如TCP/IP,UDP/IP协议等)下快速高效开发。 Apache Mina也称为:  NIO框架  客户端/服务端框架(典型的C/S架构)  网络套接字(networking...

    Apache +mina使用介绍(包含API介绍)

    基于java NIO技术的TCP/UDP应用程序开发,串口通讯开发。 内部包含实例应用,有利于新手上手!

    《Netty in action》中文版

    1. Netty 与Java NIO APIs 2. 你的第一个netty应用程式 3. Netty 起源 第二部分: netty的核心部分 4. 数据传输Transports 5.缓冲区 Buffers 6. channel处理程式ChannelHandler 7.编解码 Codec 8. ChannelHandlers与...

Global site tag (gtag.js) - Google Analytics