---
title: "NIO 与 QUEUE 的结合"
author: "cary"
date: "2007-10-01T15:43:04Z"
tags: []
slug: "nio-queue"
draft: false
lastmod: "2007-10-01T15:43:04Z"
id: 128617
url: "https://cary.iteye.com/blog/128617"
---

写了一段时间的NIO通信部分，在不断的摸索中提升，但是也有很多不足的地方，下面是一些在写的过程解决的小方法。  
QUEUE的认识让我在写程序中如鱼得水，在NIO通信中经常利用到  
Queue queue = new LinkedList();  
1: 在NIO通信中利用QUEUE来处理信息的发送和接受

java 代码

01. while (selector.select() &gt; 0) {
02. Set     readyKeys =  selector.selectedKeys();
03. Iterator  it = readyKeys.iterator();
04. while (it.hasNext()) {
05. try {
06. SelectionKey   key = (SelectionKey) it.next();
07. it.remove();
08. if (key.isAcceptable()) {
09. ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
10. SocketChannel socketChannel = (SocketChannel) ssc.accept();
11. socketChannel.configureBlocking(false);
12. socketChannel.register(selector, SelectionKey.OP\_READ
13. | SelectionKey.OP\_WRITE);
14. }
15. if (key.isReadable()) {
16. receive(key);
17. }
18. if ( key.isWritable()) {
19. send(key);
20. }
21. } catch (IOException e) {
22. e.printStackTrace();
23. try {
24. if (key != null) {
25. key.cancel();// 释放和关闭key
26. key.channel().close();
27. }
28. } catch (Exception ex) {
29. logger.error(ex);
30. }   }
31. }// #while
32. ｝

定义相关相关队列

java 代码

1. 定义接受和发送队列
2. Queue&lt;string&gt;&lt;/string&gt;   reciveQueue = new LinkedList&lt;string&gt;&lt;/string&gt;();
3. Queue&lt;string&gt;&lt;/string&gt;   sendQueue = new LinkedList&lt;string&gt;&lt;/string&gt;();

关于revceive(key)就可以这样处理了

java 代码

01. public void receive(SelectionKey key) throws IOException {
02. SocketChannel socketChannel = (SocketChannel) key.channel();
03. socketChannel.read(readBuff);
04. readBuff.flip();
05. String rmsg = decode(readBuff);
06. //将接受到的数据放到队列中
07. reciveQueue.offer(rmsg );
08. ByteBuffer tempBuffer = encode(msg);
09. readBuff.position(tempBuffer.limit());
10. readBuff.compact();
11. }

关于Send(key)

java 代码

01. public void send(SelectionKey key) throws IOException {
02. SocketChannel socketChannel = (SocketChannel) key.channel();
03. String msg = null;
04. ByteBuffer reBuffer = null;
05. //队列中取出需要发送的信息
06. while ((msg = sendQueue.poll()) != null) {
07. reBuffer = encode(msg);
08. writeBuff.put(reBuffer);
09. writeBuff.flip();
10. while (writeBuff.hasRemaining())
11. socketChannel.write(writeBuff);
12. writeBuff.position(reBuffer.limit());
13. writeBuff.compact();
14. }
15. }

2:关于心跳协议  
    以前在处理这部分时很烦恼，在网上搜了很多也问了一些人。遇到QUEUE后，我开始利用QUEUE来处理消息，也解决了心跳包的发送烦恼；可以利用定时器在固定时间内象队列中offer心跳包；

3:因为QUEUE是线程安全的，所以在QUEUE的处理上带来了很多方便，可以在利用多线程完成通信和数据的处理异步方式，利用NIO完成数据的接受，然后将reciveQueue注入到另一个数据处理线程，来完成异步处理的效果。