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

NIO-TCP简单实例

    博客分类:
  • NIO
阅读更多
Java Nio系列教程;http://www.iteye.com/magazines/132-Java-NIO
Channel接口定义:http://donald-draper.iteye.com/blog/2369111
AbstractInterruptibleChannel接口定义:http://donald-draper.iteye.com/blog/2369238
SelectableChannel接口定义:http://donald-draper.iteye.com/blog/2369317
SelectionKey定义:http://donald-draper.iteye.com/blog/2369499
SelectorProvider定义:http://donald-draper.iteye.com/blog/2369615
AbstractSelectableChannel定义:http://donald-draper.iteye.com/blog/2369742
NetworkChannel接口定义:http://donald-draper.iteye.com/blog/2369773
ServerSocketChannel定义:http://donald-draper.iteye.com/blog/2369836
ServerSocketChannelImpl解析:http://donald-draper.iteye.com/blog/2370912
Selector定义:http://donald-draper.iteye.com/blog/2370015
AbstractSelector定义:http://donald-draper.iteye.com/blog/2370138
SelectorImpl分析 :http://donald-draper.iteye.com/blog/2370519
WindowsSelectorImpl解析一(FdMap,PollArrayWrapper):
http://donald-draper.iteye.com/blog/2370811
WindowsSelectorImpl解析二(选择操作,通道注册,通道反注册,选择器关闭等):
http://donald-draper.iteye.com/blog/2370862
SocketChannel接口定义:http://donald-draper.iteye.com/blog/2371218
SocketChannelImpl 解析一(通道连接,发送数据):http://donald-draper.iteye.com/blog/2372364
SocketChannelImpl 解析二(发送数据后续):http://donald-draper.iteye.com/blog/2372548
SocketChannelImpl 解析三(接收数据):http://donald-draper.iteye.com/blog/2372590
SocketChannelImpl 解析四(关闭通道等) :http://donald-draper.iteye.com/blog/2372717
MembershipKey定义:http://donald-draper.iteye.com/blog/2372947
MulticastChanne接口定义:http://donald-draper.iteye.com/blog/2373009
MembershipKeyImpl 简介:http://donald-draper.iteye.com/blog/2373066
DatagramChannel定义:http://donald-draper.iteye.com/blog/2373046
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
     Java Nio从JDK1.4之后,才加入到JDK中,在JDK1.1之后,1.4之前,网络编程一般用阻塞BIO,NIO为非阻的IO,NIO主要包括Selector,Channel(Tcp:ServerSocket,Socket;
Udp:Datagram,File;Pipe:Sink,Source),Buffer,SelectionKey等相关的概念在网上有很多这里就不说了,今天文章我们用NIO写一个基于TCP的简单Server和Client。TCP在NIO主要基于ServerSocketChannel和ServerChannel,下面来看实例。
服务端:
package nio.simplesocket;

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

/**
 * Sever
 * @author donald
 * 2017年4月11日
 * 下午9:24:03
 */
public class NIOServer {
	//manager the channel
	private Selector selector;
	/**
	 * stat Server
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException{
		NIOServer server = new NIOServer();
		server.initServer("192.168.32.126", 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
		ServerSocketChannel serverChannel = ServerSocketChannel.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_ACCEPT);
		}
	/**
	 * 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.isAcceptable()){
					ServerSocketChannel server = (ServerSocketChannel)key.channel();
					SocketChannel channel = server.accept();
					channel.configureBlocking(false);
					channel.write(ByteBuffer.wrap(new String("Hello client!").getBytes()));
					channel.register(this.selector, SelectionKey.OP_READ);
				}
				else if (key.isReadable()) read(key);
			}
			
		}
	}
	/**
	 * deal with the message come from the client
	 * @param key
	 * @throws IOException 
	 */
	public void read(SelectionKey key) throws IOException{
		SocketChannel channel = (SocketChannel) key.channel();
		ByteBuffer buf = ByteBuffer.allocate(100);
		channel.read(buf);
		byte[] data = buf.array();
		String msg = new String(data).trim();
		System.out.println("message come from client:"+msg);
	}
	
}

客户端:
package nio.simplesocket;

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

/**
 * Client
 * @author donald
 * 2017年4月11日
 * 下午9:24:09
 */
public class NIOClient {
	//manager the channel
	private Selector selector;
	/**
	 * stat Client
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException{
		NIOClient client = new NIOClient();
		client.initClient("192.168.32.126",10000);
		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
		SocketChannel channel = SocketChannel.open();
		// set no blocking mode
		channel.configureBlocking(false);
		//connect the Server
		channel.connect(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_CONNECT);
		}
	/**
	 * 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.isConnectable()){
					SocketChannel channel = (SocketChannel)key.channel();
                    //during connecting, finish the connect
                    if(channel.isConnectionPending()){
                    	channel.finishConnect();
                    }
					channel.configureBlocking(false);
					channel.write(ByteBuffer.wrap(new String("Hello Server!").getBytes()));
					channel.register(this.selector, SelectionKey.OP_READ);
				}
				else if (key.isReadable()) read(key);
			}
			
		}
	}
	/**
	 * deal with the message come from the server
	 * @param key
	 * @throws IOException 
	 */
	public void read(SelectionKey key) throws IOException{
		SocketChannel channel = (SocketChannel) key.channel();
		ByteBuffer buf = ByteBuffer.allocate(100);
		channel.read(buf);
		byte[] data = buf.array();
		String msg = new String(data).trim();
		System.out.println("message come from server:"+msg);
	}	
}

先启动NIOServer,在启动NIOClient,控制台输出:
NIOServer:
=========The Server is start!===========
message come from client:Hello Server!

NIOClient:
===========The Client is start!===========
message come from server:Hello client!

附:测试Buffer
package nio;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
/**
 * 协议测试
 * @author donald
 * 2017年4月10日
 * 下午9:26:57
 */
public class testByteBuffer {
	public static void main(String[] args) {
		ByteBuffer[] proctols = null;//
		proctols = new ByteBuffer[2];
		ByteBuffer protocolBuffer = null;//协议编码
		protocolBuffer = ByteBuffer.allocate(6);
		try {
			System.out.println("ProtocolCode String length:"+new String("300000").getBytes("UTF-8").length);
			protocolBuffer.put(new String("300000").getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		System.out.println("ProtocolCode length:"+protocolBuffer.position());
		proctols[0] = protocolBuffer;
		ByteBuffer dataBuffer = null;//操作数
		dataBuffer = ByteBuffer.allocate(8);
		dataBuffer.putInt(15);
		dataBuffer.putInt(6);
		System.out.println("data length:"+dataBuffer.position());
		proctols[1] = dataBuffer;
//		protocolBuffer.compact();//针对数据太大,缓冲区一次装不完的情况
		protocolBuffer.clear();
		try {
			protocolBuffer.put(new String("300100").getBytes("UTF-8"));
			System.out.println("ProtocolCode length:"+protocolBuffer.position());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
//		dataBuffer.compact();
		dataBuffer.clear();
		dataBuffer.putInt(17);
		dataBuffer.putInt(8);
		System.out.println("data length:"+dataBuffer.position());
	}
}
0
0
分享到:
评论

相关推荐

    Java Socket编程实例(四)- NIO TCP实践

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

    Mina Tcp实例

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

    netty-demo实例

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

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

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

    基于naga开发的TCP客户端/服务器程序

    同样在继承该基础类时,可以在继承类中添加各种需要的引用及必要的方法,实例在 communication.tcp.example.TCPClientUnit体现,重写revDataAndParse方法如下: /** * 处理数据将数据置于队列中,...

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

     Tcp服务端与客户端的JAVA实例源代码,一个简单的Java TCP服务器端程序,别外还有一个客户端的程序,两者互相配合可以开发出超多的网络程序,这是最基础的部分。 递归遍历矩阵 1个目标文件,简单! 多人聊天室 3...

    apache mina socket实例

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

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

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

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

     Tcp服务端与客户端的JAVA实例源代码,一个简单的Java TCP服务器端程序,别外还有一个客户端的程序,两者互相配合可以开发出超多的网络程序,这是最基础的部分。 递归遍历矩阵 1个目标文件,简单! 多人聊天室 3...

    spring-boot示例项目

    netty|[基于BIO、NIO等tcp服务器搭建介绍](https://github.com/smltq/spring-boot-demo/blob/master/netty) ### Spring Cloud 模块 模块名称|主要内容 ---|--- cloud-oauth2-auth-code|[基于spring cloud...

    精通并发与netty视频教程(2018)视频教程

    42_NIO网络编程实例剖析 43_NIO网络编程深度解析 44_NIO网络客户端编写详解 45_深入探索Java字符集编解码 46_字符集编解码全方位解析 47_Netty服务器与客户端编码模式回顾及源码分析准备 48_Netty与NIO系统总结及NIO...

    精通并发与 netty 视频教程(2018)视频教程

    39_NIO中Scattering与Gathering深度解析 40_Selector源码深入分析 41_NIO网络访问模式分析 42_NIO网络编程实例剖析 43_NIO网络编程深度解析 44_NIO网络客户端编写详解 45_深入探索Java字符集编解码 46_字符集编解码...

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

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

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

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

    mina2框架+项目实例教程

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

    精通并发与netty 无加密视频

    第1讲:学习的要义 第2讲:Netty宏观理解 第3讲:Netty课程大纲深度解读 ...第90讲:TCP粘包与拆包实例演示及分析 第91讲:Netty自定义协议与TCP粘包拆包问题解决之道 第92讲:精通并发与Netty课程总结与展望

    BAT面试真题最新(涵盖全方面)

    Selector:通过调⽤用Selector的select⽅方法可以从所有的Channel中找到需要服务的实例例 (例例如 Accept,read等) Channel:代表⼀一个可以被⽤用于Poll操作的对象(可以是⽂文件流也可以使⽹网络流), ...

    java开源包1

    开发它是用于在UTF-8 Oracle实例中使用ASCII编码的Oracle 数据库中来正确的传输非ASCII字符。 Java模板语言 Beetl Beetl,是Bee Template Language的缩写,它绝不是简单的另外一种模板引擎,而是新一代的模板引擎,...

Global site tag (gtag.js) - Google Analytics