Java NIO编写Socket服务器的一个例子

最近一直在忙着JAVA NIO的知识,花了一下午的时间,总算写出了一个可以运行的程序,废话少说,上代码!

Java代码:

  1. import java.io.IOException;  
  2. import java.net.InetSocketAddress;  
  3. import java.net.ServerSocket;  
  4. import java.nio.ByteBuffer;  
  5. import java.nio.channels.SelectionKey;  
  6. import java.nio.channels.Selector;  
  7. import java.nio.channels.ServerSocketChannel;  
  8. import java.nio.channels.SocketChannel;  
  9. import java.util.Iterator;  
  10. import java.util.Set;  
  11.  
  12. public class NIOServer {  
  13.       
  14.     /*标识数字*/ 
  15.     private  int flag = 0;  
  16.     /*缓冲区大小*/ 
  17.     private  int BLOCK = 4096;  
  18.     /*接受数据缓冲区*/ 
  19.     private  ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK);  
  20.     /*发送数据缓冲区*/ 
  21.     private  ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK);  
  22.     private  Selector selector;  
  23.  
  24.     public NIOServer(int port) throws IOException {  
  25.         // 打开服务器套接字通道  
  26.         ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();  
  27.         // 服务器配置为非阻塞  
  28.         serverSocketChannel.configureBlocking(false);  
  29.         // 检索与此通道关联的服务器套接字  
  30.         ServerSocket serverSocket = serverSocketChannel.socket();  
  31.         // 进行服务的绑定  
  32.         serverSocket.bind(new InetSocketAddress(port));  
  33.         // 通过open()方法找到Selector  
  34.         selector = Selector.open();  
  35.         // 注册到selector,等待连接  
  36.         serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);  
  37.         System.out.println("Server Start----8888:");  
  38.     }  
  39.  
  40.  
  41.     // 监听  
  42.     private void listen() throws IOException {  
  43.         while (true) {  
  44.             // 选择一组键,并且相应的通道已经打开  
  45.             selector.select();  
  46.             // 返回此选择器的已选择键集。  
  47.             Set<SelectionKey> selectionKeys = selector.selectedKeys();  
  48.             Iterator<SelectionKey> iterator = selectionKeys.iterator();  
  49.             while (iterator.hasNext()) {          
  50.                 SelectionKey selectionKey = iterator.next();  
  51.                 iterator.remove();  
  52.                 handleKey(selectionKey);  
  53.             }  
  54.         }  
  55.     }  
  56.  
  57.     // 处理请求  
  58.     private void handleKey(SelectionKey selectionKey) throws IOException {  
  59.         // 接受请求  
  60.         ServerSocketChannel server = null;  
  61.         SocketChannel client = null;  
  62.         String receiveText;  
  63.         String sendText;  
  64.         int count=0;  
  65.         // 测试此键的通道是否已准备好接受新的套接字连接。  
  66.         if (selectionKey.isAcceptable()) {  
  67.             // 返回为之创建此键的通道。  
  68.             server = (ServerSocketChannel) selectionKey.channel();  
  69.             // 接受到此通道套接字的连接。  
  70.             // 此方法返回的套接字通道(如果有)将处于阻塞模式。  
  71.             client = server.accept();  
  72.             // 配置为非阻塞  
  73.             client.configureBlocking(false);  
  74.             // 注册到selector,等待连接  
  75.             client.register(selector, SelectionKey.OP_READ);  
  76.         } else if (selectionKey.isReadable()) {  
  77.             // 返回为之创建此键的通道。  
  78.             client = (SocketChannel) selectionKey.channel();  
  79.             //将缓冲区清空以备下次读取  
  80.             receivebuffer.clear();  
  81.             //读取服务器发送来的数据到缓冲区中  
  82.             count = client.read(receivebuffer);   
  83.             if (count > 0) {  
  84.                 receiveText = new String( receivebuffer.array(),0,count);  
  85.                 System.out.println("服务器端接受客户端数据--:"+receiveText);  
  86.                 client.register(selector, SelectionKey.OP_WRITE);  
  87.             }  
  88.         } else if (selectionKey.isWritable()) {  
  89.             //将缓冲区清空以备下次写入  
  90.             sendbuffer.clear();  
  91.             // 返回为之创建此键的通道。  
  92.             client = (SocketChannel) selectionKey.channel();  
  93.             sendText="message from server--" + flag++;  
  94.             //向缓冲区中输入数据  
  95.             sendbuffer.put(sendText.getBytes());  
  96.              //将缓冲区各标志复位,因为向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位  
  97.             sendbuffer.flip();  
  98.             //输出到通道  
  99.             client.write(sendbuffer);  
  100.             System.out.println("服务器端向客户端发送数据--:"+sendText);  
  101.             client.register(selector, SelectionKey.OP_READ);  
  102.         }  
  103.     }  
  104.  
  105.     /**  
  106.      * @param args  
  107.      * @throws IOException  
  108.      */ 
  109.     public static void main(String[] args) throws IOException {  
  110.         // TODO Auto-generated method stub  
  111.         int port = 8888;  
  112.         NIOServer server = new NIOServer(port);  
  113.         server.listen();  
  114.     }  

Java代码:

  1. import java.io.IOException;  
  2. import java.net.InetSocketAddress;  
  3. import java.nio.ByteBuffer;  
  4. import java.nio.channels.SelectionKey;  
  5. import java.nio.channels.Selector;  
  6. import java.nio.channels.SocketChannel;  
  7. import java.util.Iterator;  
  8. import java.util.Set;  
  9.  
  10. public class NIOClient {  
  11.  
  12.     /*标识数字*/ 
  13.     private static int flag = 0;  
  14.     /*缓冲区大小*/ 
  15.     private static int BLOCK = 4096;  
  16.     /*接受数据缓冲区*/ 
  17.     private static ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK);  
  18.     /*发送数据缓冲区*/ 
  19.     private static ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK);  
  20.     /*服务器端地址*/ 
  21.     private final static InetSocketAddress SERVER_ADDRESS = new InetSocketAddress(  
  22.             "localhost"1111);  
  23.  
  24.     public static void main(String[] args) throws IOException {  
  25.         // TODO Auto-generated method stub  
  26.         // 打开socket通道  
  27.         SocketChannel socketChannel = SocketChannel.open();  
  28.         // 设置为非阻塞方式  
  29.         socketChannel.configureBlocking(false);  
  30.         // 打开选择器  
  31.         Selector selector = Selector.open();  
  32.         // 注册连接服务端socket动作  
  33.         socketChannel.register(selector, SelectionKey.OP_CONNECT);  
  34.         // 连接  
  35.         socketChannel.connect(SERVER_ADDRESS);  
  36.         // 分配缓冲区大小内存  
  37.           
  38.         Set<SelectionKey> selectionKeys;  
  39.         Iterator<SelectionKey> iterator;  
  40.         SelectionKey selectionKey;  
  41.         SocketChannel client;  
  42.         String receiveText;  
  43.         String sendText;  
  44.         int count=0;  
  45.  
  46.         while (true) {  
  47.             //选择一组键,其相应的通道已为 I/O 操作准备就绪。  
  48.             //此方法执行处于阻塞模式的选择操作。  
  49.             selector.select();  
  50.             //返回此选择器的已选择键集。  
  51.             selectionKeys = selector.selectedKeys();  
  52.             //System.out.println(selectionKeys.size());  
  53.             iterator = selectionKeys.iterator();  
  54.             while (iterator.hasNext()) {  
  55.                 selectionKey = iterator.next();  
  56.                 if (selectionKey.isConnectable()) {  
  57.                     System.out.println("client connect");  
  58.                     client = (SocketChannel) selectionKey.channel();  
  59.                     // 判断此通道上是否正在进行连接操作。  
  60.                     // 完成套接字通道的连接过程。  
  61.                     if (client.isConnectionPending()) {  
  62.                         client.finishConnect();  
  63.                         System.out.println("完成连接!");  
  64.                         sendbuffer.clear();  
  65.                         sendbuffer.put("Hello,Server".getBytes());  
  66.                         sendbuffer.flip();  
  67.                         client.write(sendbuffer);  
  68.                     }  
  69.                     client.register(selector, SelectionKey.OP_READ);  
  70.                 } else if (selectionKey.isReadable()) {  
  71.                     client = (SocketChannel) selectionKey.channel();  
  72.                     //将缓冲区清空以备下次读取  
  73.                     receivebuffer.clear();  
  74.                     //读取服务器发送来的数据到缓冲区中  
  75.                     count=client.read(receivebuffer);  
  76.                     if(count>0){  
  77.                         receiveText = new String( receivebuffer.array(),0,count);  
  78.                         System.out.println("客户端接受服务器端数据--:"+receiveText);  
  79.                         client.register(selector, SelectionKey.OP_WRITE);  
  80.                     }  
  81.  
  82.                 } else if (selectionKey.isWritable()) {  
  83.                     sendbuffer.clear();  
  84.                     client = (SocketChannel) selectionKey.channel();  
  85.                     sendText = "message from client--" + (flag++);  
  86.                     sendbuffer.put(sendText.getBytes());  
  87.                      //将缓冲区各标志复位,因为向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位  
  88.                     sendbuffer.flip();  
  89.                     client.write(sendbuffer);  
  90.                     System.out.println("客户端向服务器端发送数据--:"+sendText);  
  91.                     client.register(selector, SelectionKey.OP_READ);  
  92.                 }  
  93.             }  
  94.             selectionKeys.clear();  
  95.         }  
  96.     }  

个人感觉,JAVA NIO的操作时麻烦了不少,但是无疑这样做效率会得到很大的提升。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/387473.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2.5 map

#include<map> key/value对 采用红黑树实现&#xff0c;键值不允许重复 用法与set类似 创建map&#xff1a; map<string, float> m; m["haha"] 11.1; m["hehe"] 22.2; for (map<string, float>::iterator it m.begin(); it ! m.en…

在js传递参数中含加号(+)的处理方式

一般情况下&#xff0c;url中的参数应使用 url 编码规则&#xff0c;即把参数字符串中除了 “ - "、" _ " 、" . "之外的所有非字母数字字符都将被替换成百分号&#xff08;%&#xff09;后跟两位十六进制数&#xff0c;空格则编码为加号&#xff08;…

二 SVN代码冲突的解决

问题&#xff1a; A和B都是最新的代码&#xff0c;A修改了代码提交了&#xff0c;B也修改了代码&#xff0c;但是B提交的时候出现冲突的问题。 解决方案&#xff1a;编辑冲突 解决冲突&#xff1a; 方法一&#xff1a;将文件里面冲突的描述去掉&#xff0c;重新提交 方法二&…

Android7.0反射类找不到的问题

Java中使用反射的地方较多&#xff0c;尤其是各种框架中。最近在Android7.0的项目中遇到个问题很奇怪&#xff0c;反射使用的类找不到了&#xff0c;但是编译的时候没问题啊。然后在代码中使用非反射的方式调用代码也是没有问题的&#xff0c;这时奇怪的现象出现了&#xff0c;…

2.6 multimap

#include<map> multimap的元素插入、删除、查找与map不同 multimap元素的插入&#xff1a;&#xff08;未提供mm[key]value插入方式&#xff09; multimap<string, double> mm; mm.insert(pair<string, double>("haha", 11.1)); mm.insert(pai…

Mybatis学习笔记18 - 缓存

两级缓存&#xff1a; 一级缓存&#xff1a;&#xff08;本地缓存&#xff09;&#xff1a;sqlSession级别的缓存。一级缓存是一直开启的&#xff1b;SqlSession级别的一个Map 数据库同一次会话期间查询到的数据会放在本地缓存中。以后如果需要获取相同的数据&#xff0c;直接从…

2.7 deque

#include<deque> 双端队列容器 注意&#xff1a;头入队时伴随的是尾出队&#xff1b;提供中间元素的更新和删除操作。 与vector一样&#xff0c;采用线性表顺序存储结构 deque采用分块的线性存储结构来存储数据&#xff0c;每块大小一般为512字节 所有deque块由一个…

APK 加壳方法

下载工具http://download.csdn.net/download/sys025/8958363一款免费的为apk加固的工具。 特别说明&#xff1a;加固后需要重新签名apk才能安装。加固的apk包会比未加固的大一些。 jarsigner -verbose -keystore dms.keystore -storepass pactera -keypass pactera -sigfile CE…

Java DSL简介(收集整理)

一、领域特定语言&#xff08;DSL&#xff09; 领域特定语言&#xff08;DSL&#xff09;通常被定义为一种特别针对某类特殊问题的计算机语言&#xff0c;它不打算解决其领域外的问题。对于DSL的正式研究已经持续很多年&#xff0c;直 到最近&#xff0c;在程序员试图采用最易读…

[转]JSon数据解析的四种方式

转至http://blog.csdn.net/enuola/article/details/7903632 作为一种轻量级的数据交换格式&#xff0c;json正在逐步取代xml&#xff0c;成为网络数据的通用格式。 有的json代码格式比较混乱&#xff0c;可以使用此“http://www.bejson.com/”网站来进行JSON格式化校验&#xf…

2.8 list

#include<list> 双向循环链表 list结点的三个域&#xff1a;数据域、前驱元素指针域、后继元素指针域 对于list的迭代器&#xff0c;只有或--的操作&#xff0c;无n或-n的操作 创建list对象&#xff1a; list<int> l; list<int> l(10); 插入和遍历&…

Spring AOP两种实现机制是什么?

Spring AOP两种实现机制是什么&#xff1f; 1.如果是有接口声明的类进行AOP 时&#xff0c;spring调用的是java.lang.reflection.Proxy 类来做处理 2.如果是没有接口声明的类时&#xff0c; spring通过cglib包和内部类来实现 在AOP&#xff0c;权限控制&#xff0c;事务管理等…

iOS开发UI篇—Quartz2D使用(绘图路径)

1 //1.获取图形上下文 2 CGContextRef ctxUIGraphicsGetCurrentContext(); 3 //2.绘图&#xff08;画线&#xff09; 4 //设置起点 5 CGContextMoveToPoint(ctx, 20, 20); 6 //设置终点 7 CGContextAddLineToPoint(ctx, 200, 300); 8 //渲染 9…

2.9 bitset

#include<bitset> bitset容器是一个bit位元素的序列容器&#xff0c;每个元素只占一个bit位&#xff0c;取值为0或1&#xff0c;因而很节省内存空间。 bitset<n> b; b.any() 是否有1 b.none() 是否无1 b.count() 1的个数 b.size() 大小 b[pos] 访问 b.…

C# 谈谈Interface和通过Interface传递web页面数据

接口&#xff1a;描述可属于任何类或结构的一组相关功能&#xff0c;通过interface关键字来声明&#xff1b;接口只包含方法、委托或事件和属性的签名&#xff08;接口包含的成员&#xff09;、不能包含字段&#xff08;因为字段是包含数据的&#xff09;。方法的实现是“继承”…

Spring支持如下5种作用域

当通过Spring容器创建一个Bean实例时&#xff0c;不仅可以完成Bean实例的实例化&#xff0c;还可以为Bean指定特定的作用域。Spring支持如下5种作用域&#xff1a; singleton&#xff1a;单例模式&#xff0c;在整个Spring IoC容器中&#xff0c;使用singleton定义的Bean将只有…

RBAC授权

给用户授予RBAC权限没有权限会报如下错误&#xff1a;执行查看资源报错&#xff1a; unable to upgrade connection: Forbidden (userkubernetes, verbcreate, resourcenodes, subresourceproxy)[roottest4 ~]# kubectl exec -it http-test-dm2-6dbd76c7dd-cv9qf sh error: una…

出卷子

http://chujuanzi.com/ 出卷子 涵盖初高中全部学科题库&#xff0c;全国名校试卷最快更新。试卷新、试题全、解析准、完全免费&#xff0c;提供丰富试题辅助教师有效出试卷&#xff0c;组卷方便快捷。&#xff08;高中语文 高中数学 高中英语 高中物理 高中化学 高中生物 高中政…

2.10 stack

#include<stack> 后进先出 Last In First Out LIFO 插入和删除元素只能在表的一端进行。 插入端 栈顶 Stack Top 入栈 Push 删除端 栈底 Stack Bottom 出栈 Pop stack<int> s; s.push(1); //入栈 int i s.top(); //获得栈顶元素 s.pop(); //出栈 s.size…

13结构型模式之桥接模式

概念 Bridge 模式又叫做桥接模式&#xff0c;是构造型的设计模式之一。Bridge模式基于类的最小设计原则&#xff0c;通过使用封装&#xff0c;聚合以及继承等行为来让不同的类承担不同的责任。它的主要特点是把抽象&#xff08;abstraction&#xff09;与行为实现&#xff08;i…