casualjim
4/14/2011 - 2:21 PM

grizzly-server.scala

import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.{TimeUnit, Executors}
import java.util.Date
import javax.servlet.http.{HttpServletRequest, HttpServletResponse, HttpServlet}
import javax.servlet.{ServletContext, ServletConfig}
import org.glassfish.grizzly.comet._
import org.glassfish.grizzly.http.HttpRequestPacket
import collection.JavaConversions._
import org.glassfish.grizzly.http.server.{Response, HttpServer}
import org.glassfish.grizzly.servlet.ServletHandler
import org.glassfish.grizzly.websockets._
import org.glassfish.grizzly.websockets.frame.Frame

object Main {

  val timer = Executors.newSingleThreadScheduledExecutor


  class TimedWebSocketApplication extends WebSocketApplication[WebSocket] {

    def onMessage(p1: WebSocket, p2: Frame) {
      println("message received")
      timer.scheduleAtFixedRate(new Runnable {
        def run() {
          println("sending time")
          p1.send(Frame.createTextFrame("the time: " + (new Date).toString))
        }
      }, 500, 500, TimeUnit.MILLISECONDS)
    }

    
  }

  class EchoWebSocketApplication extends WebSocketApplication[WebSocket] {
    def isApplicationRequest(request: HttpRequestPacket) = {
      "/echo".equals(request.getRequestURI)
    }



    def onMessage(p1: WebSocket, p2: Frame) {
      p1.send(Frame.createTextFrame("ECHO: " + p2.getAsText))
    }
  }

  class TimeCometHandler(httpResponse: HttpServletResponse) extends CometHandler[String] {

    private var _context: CometContext[String] = _
    private var _response: Response = _

    def onInterrupt(p1: CometEvent[_]) {
      println("client disconnect?, interrupt, event type: " + p1.getType)
    }


    def onTerminate(p1: CometEvent[_]) {
      println("terminating, event type: " + p1.getType)
    }

    def onInitialize(p1: CometEvent[_]) {
      println("initializing")
    }

    def onEvent(p1: CometEvent[_]) {
      println("handling event: " + p1.getType)
      if (CometEvent.Type.NOTIFY == p1.getType) {
        val w = httpResponse.getWriter
        w.println(p1.attachment.toString)
        w.flush()
      }
    }

    def setCometContext(p1: CometContext[String]) {
      println("setting comet context")
      _context = p1
    }

    def getCometContext = _context

    def setResponse(p1: Response) {
      println("setting response")
      _response = p1
    }

    def getResponse = _response
  }

  class TimeCometServlet extends HttpServlet {
    var contextPath: String = _

    override def init(config: ServletConfig) {
      val context: ServletContext = config.getServletContext
      contextPath = context.getContextPath 
      val engine: CometEngine = CometEngine.getEngine
      val cometContext: CometContext[_] = engine.register(contextPath)
      cometContext.setExpirationDelay(5 * 30 * 1000)
    }

    override def doGet(req: HttpServletRequest, resp: HttpServletResponse) {
      println("Entering timed_comet")

      val handler = new TimeCometHandler(resp)
      timer.scheduleAtFixedRate(new Runnable {
        def run() {
          val engine = CometEngine.getEngine
          val context = engine.getCometContext[String](contextPath)
          context.notify("The current time: " + (new Date).toString)

        }
      }, 500, 500, TimeUnit.MILLISECONDS)
      val engin = CometEngine.getEngine
      val cont = engin.getCometContext[String](contextPath)
      cont.addCometHandler(handler)
      cont.notify("connected")

      val w = resp.getWriter
      w.write("success")
      w.flush
    }
  }


  def main(args: Array[String]) {
    println("this works already.")
    val server = HttpServer.createSimpleServer("src/main/webapp", 8888)
    server.getServerConfiguration.setHttpServerName("Backchat WebSocket Server")
    server.getServerConfiguration.setName("Backchat WebSocket Server")
    server.getListeners foreach { l =>
      l.registerAddOn(new WebSocketAddOn)
      l.registerAddOn(new CometAddOn)
    }

    server.getServerConfiguration.addHttpHandler(new ServletHandler(new TimeCometServlet), "/timed_comet")
//    WebSocketEngine.getEngine.registerApplication("/echo", new EchoWebSocketApplication)
    WebSocketEngine.getEngine.registerApplication("/timer", new TimedWebSocketApplication)

    try {
      server.start();
      println("Press any key to stop the server...");
      System.in.read();
    } finally {
      // stop the server
      timer.shutdownNow
      server.stop();
    }
  }
}