NIO 入门 实例
来源:互联网 发布:知名网络集成商有哪些? 编辑:程序博客网 时间:2024/06/03 12:43
NIOServer
package com.nio.test;import java.io.IOException;import java.net.InetSocketAddress;import java.net.ServerSocket;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;import java.util.Set;public class NIOServer implements Runnable{privateServerSocketChannel serverSocketChannel;privateServerSocket serverSocket;privateSelector selector;/*标识数字*/ private int flag = 0; /*缓冲区大小*/ private int BLOCK = 4096; /*接受数据缓冲区*/ private ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK); /*发送数据缓冲区*/ private ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK); public NIOServer(int port) { try { //打开服务器管道 serverSocketChannel = ServerSocketChannel.open(); // 服务器配置为非阻塞 serverSocketChannel.configureBlocking(false); //检索与此通道关联的服务器套接字 serverSocket=serverSocketChannel.socket(); //进行服务的绑定 serverSocket.bind(new InetSocketAddress(port)); //通过open获取selector selector=Selector.open();// 注册到selector,等待连接 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("bind 8888 port........."); } catch (IOException e) {e.printStackTrace();}}public void run() {while (true) {// 选择一组键,并且相应的通道已经打开 try {selector.select();Set<SelectionKey> selectionKeys = selector.selectedKeys();Iterator<SelectionKey>iterator = selectionKeys.iterator();while (iterator.hasNext()) {SelectionKey selectionKey = (SelectionKey) iterator.next();iterator.remove();if (flag == 10) {System.exit(0);}handler(selectionKey);}} catch (Exception e) {System.exit(0);}}}private void handler(SelectionKey selectionKey) throws Exception { // 接受请求 ServerSocketChannel server = null; SocketChannel client = null; String receiveText; String sendText; int count=0; if (selectionKey.isAcceptable()) {server =(ServerSocketChannel) selectionKey.channel(); client = server.accept(); client.configureBlocking(false); client.register(selector, SelectionKey.OP_READ);}else if (selectionKey.isReadable()) {client =(SocketChannel) selectionKey.channel();receivebuffer.clear();count =client.read(receivebuffer);if (count > 0) {receiveText = new String(receivebuffer.array(),0,count); System.out.println("服务器端接受客户端数据--:"+receiveText); client.register(selector, SelectionKey.OP_WRITE); }}else if (selectionKey.isWritable()) {sendbuffer.clear();client=(SocketChannel) selectionKey.channel();sendText="message form server ---"+flag++;sendbuffer.put(sendText.getBytes());sendbuffer.flip();//client.write(sendbuffer);System.out.println("服务器端向客户端发送数据---:"+sendText);client.register(selector, SelectionKey.OP_READ);}else if (selectionKey.isConnectable()) {System.out.println("selectionKey is Connectable .");}}public static void main(String[] args) {int port = 8888;NIOServer nioServer = new NIOServer(port);new Thread(nioServer).start();}}
NIOClient
package com.nio.test;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;import java.util.Set;public class NIOClient implements Runnable{privateSocketChannel serverSocket;privateSelector selector;/*标识数字*/ private int flag = 0; /*缓冲区大小*/ private int BLOCK = 4096; /*接受数据缓冲区*/ private ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK); /*发送数据缓冲区*/ private ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK); public NIOClient(int port) { try { serverSocket = SocketChannel.open(); // 配置为非阻塞 serverSocket.configureBlocking(false); //进行连接 serverSocket.connect(new InetSocketAddress(port)); //通过open获取selector selector=Selector.open();// 注册到selector,等待连接 serverSocket.register(selector, SelectionKey.OP_CONNECT); System.out.println("connet 8888 port........."); } catch (IOException e) {e.printStackTrace();}}public void run() {while (true) {// 选择一组键,并且相应的通道已经打开 try {selector.select();Set<SelectionKey> selectionKeys = selector.selectedKeys();Iterator<SelectionKey>iterator = selectionKeys.iterator();while (iterator.hasNext()) {SelectionKey selectionKey = (SelectionKey) iterator.next();iterator.remove();if (flag == 10) {System.exit(0);}handler(selectionKey);}} catch (Exception e) {e.printStackTrace();System.exit(0);}}}private void handler(SelectionKey selectionKey) throws Exception { SocketChannel client = null; String receiveText; String sendText; int count=0; if (selectionKey.isConnectable()) {System.out.println("client connect"); client = (SocketChannel) selectionKey.channel(); // 判断此通道上是否正在进行连接操作。 // 完成套接字通道的连接过程。 if (client.isConnectionPending()) { client.finishConnect(); System.out.println("完成连接!"); sendbuffer.clear(); sendbuffer.put("Hello,Server".getBytes()); sendbuffer.flip(); client.write(sendbuffer); } client.register(selector, SelectionKey.OP_READ); }else if (selectionKey.isReadable()) {client =(SocketChannel) selectionKey.channel();receivebuffer.clear();count =client.read(receivebuffer);if (count > 0) {receiveText = new String(receivebuffer.array(),0,count); System.out.println("客户端接受服务器端数据--:"+receiveText); client.register(selector, SelectionKey.OP_WRITE); }}else if (selectionKey.isWritable()) {sendbuffer.clear();client=(SocketChannel) selectionKey.channel();sendText="message form client ---"+flag++;sendbuffer.put(sendText.getBytes());sendbuffer.flip();//client.write(sendbuffer);System.out.println("客户端向服务器端发送数据---:"+sendText);client.register(selector, SelectionKey.OP_READ);}else if (selectionKey.isConnectable()) {System.out.println("selectionKey is Connectable .");}}public static void main(String[] args) {int port = 8888;NIOClient nioServer = new NIOClient(port);new Thread(nioServer).start();}}
0 0
- JAVA NIO入门实例
- NIO 入门 实例
- Java NIO简单实例(入门)
- NIO实例
- NIO--JAVA NIO 入门
- NIO入门
- nio入门
- NIO入门
- NIO 入门
- NIO入门
- NIO 入门
- NIO入门
- NIO 入门
- NIO 入门
- NIO入门
- NIO 入门
- NIO 入门
- NIO 入门
- python学习11-集合和字典
- 浅谈Web网站架构演变过程
- 关于eclipse的快捷键
- OX操作小结
- hive经典例子
- NIO 入门 实例
- 安卓实现点击两次返回后退出程序
- android在java代码中处理像素适配和国际化适配的问题
- Ubuntu之XX-NET详细教程
- Impala invalidate metadata详细使用方法说明
- Apache与Tomcat 区别联系
- Eclipse中禁用JS验证
- poj 3070(矩阵快速幂)
- Mediaproxy 与 Rtpproxy