写了一段时间的NIO通信部分,在不断的摸索中提升,但是也有很多不足的地方,下面是一些在写的过程解决的小方法。
QUEUE的认识让我在写程序中如鱼得水,在NIO通信中经常利用到
Queue queue = new LinkedList();
1: 在NIO通信中利用QUEUE来处理信息的发送和接受
java 代码
- while (selector.select() > 0) {
- Set readyKeys = selector.selectedKeys();
- Iterator it = readyKeys.iterator();
- while (it.hasNext()) {
- try {
- SelectionKey key = (SelectionKey) it.next();
- it.remove();
- if (key.isAcceptable()) {
- ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
- SocketChannel socketChannel = (SocketChannel) ssc.accept();
- socketChannel.configureBlocking(false);
- socketChannel.register(selector, SelectionKey.OP_READ
- | SelectionKey.OP_WRITE);
- }
- if (key.isReadable()) {
- receive(key);
- }
- if ( key.isWritable()) {
- send(key);
- }
- } catch (IOException e) {
- e.printStackTrace();
- try {
- if (key != null) {
- key.cancel();// 释放和关闭key
- key.channel().close();
- }
- } catch (Exception ex) {
- logger.error(ex);
- } }
- }// #while
- }
定义相关相关队列
java 代码
- 定义接受和发送队列
- Queue<string></string> reciveQueue = new LinkedList<string></string>();
- Queue<string></string> sendQueue = new LinkedList<string></string>();
关于revceive(key)就可以这样处理了
java 代码
- public void receive(SelectionKey key) throws IOException {
- SocketChannel socketChannel = (SocketChannel) key.channel();
- socketChannel.read(readBuff);
- readBuff.flip();
- String rmsg = decode(readBuff);
- //将接受到的数据放到队列中
- reciveQueue.offer(rmsg );
- ByteBuffer tempBuffer = encode(msg);
- readBuff.position(tempBuffer.limit());
- readBuff.compact();
- }
关于Send(key)
java 代码
- public void send(SelectionKey key) throws IOException {
- SocketChannel socketChannel = (SocketChannel) key.channel();
- String msg = null;
- ByteBuffer reBuffer = null;
- //队列中取出需要发送的信息
- while ((msg = sendQueue.poll()) != null) {
- reBuffer = encode(msg);
- writeBuff.put(reBuffer);
- writeBuff.flip();
- while (writeBuff.hasRemaining())
- socketChannel.write(writeBuff);
- writeBuff.position(reBuffer.limit());
- writeBuff.compact();
- }
- }
2:关于心跳协议
以前在处理这部分时很烦恼,在网上搜了很多也问了一些人。遇到QUEUE后,我开始利用QUEUE来处理消息,也解决了心跳包的发送烦恼;可以利用定时器在固定时间内象队列中offer心跳包;
3:因为QUEUE是线程安全的,所以在QUEUE的处理上带来了很多方便,可以在利用多线程完成通信和数据的处理异步方式,利用NIO完成数据的接受,然后将reciveQueue注入到另一个数据处理线程,来完成异步处理的效果。