java事件轮询_用scala实现的nio事件轮询

1.[代码]EventPoller.scala

package com.github.zhongl.mockclients

import java.nio.channels.SelectionKey

import java.nio.channels.Selector.{open => newSelector}

import scala.actors.Actor

import scala.collection.JavaConversions._

import com.github.zhongl.mockclients.Utils.silent

/**

* {@link EventPoller} is a abstract class wrap a {@link Selector} to watching channels.

* It could be extended to a acceptor( accept connection) or proccessor (handle read and write) or dispatcher (dispatch io event).

*

* @author zhongl

*/

abstract class EventPoller(val timeout: Long) extends Logging {

protected val selector = newSelector

protected val worker = new Worker

final def start: Unit = worker.start ! Poll

final def stop: Unit = worker ! Exit

protected def doHandle: PartialFunction[SelectionKey, Unit]

protected def extraExecute: PartialFunction[Command, Unit] = {

case unknown: Command => log.error("Unknown command {}", unknown)

}

private def handle(selectedKey: SelectionKey): Unit = {

if (doHandle.isDefinedAt(selectedKey)) doHandle(selectedKey)

else logErrorAndCloseChannelOf(selectedKey)

}

private def logErrorAndCloseChannelOf(key: SelectionKey): Unit = {

log.error("Close {}, because can't handle invalid key", key.channel)

silent {key.channel.close}

}

private def poll: Unit = {

if (selector.select(timeout) > 0) handleSelectedKeys

worker ! Poll

}

private def handleSelectedKeys: Unit = {

selector.selectedKeys.foreach {selectedKey => handle(selectedKey)}

selector.selectedKeys.clear

}

protected class Worker extends Actor {

final def act() = {

loop {

react {

case Poll => poll

case Exit => silent {selector.close}; exit

case unknown: Command => extraExecute(unknown)

case illegal => log.error("Illegal command {}", illegal)

}

}

}

}

abstract class Command

case class Poll extends Command

case class Exit extends Command

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值