1 5 package com.oreilly.servlet; 6 7 import java.io.*; 8 import java.net.*; 9 import java.util.*; 10 import javax.servlet.*; 11 import javax.servlet.http.*; 12 13 29 public abstract class DaemonHttpServlet extends HttpServlet { 30 31 34 protected int DEFAULT_PORT = 1313; 35 private Thread daemonThread; 36 37 45 public void init(ServletConfig config) throws ServletException { 46 super.init(config); 47 48 try { 49 daemonThread = new Daemon(this); 50 daemonThread.start(); 51 } 52 catch (Exception e) { 53 log("Problem starting socket server daemon thread" + 54 e.getClass().getName() + ": " + e.getMessage()); 55 } 56 } 57 58 67 protected int getSocketPort() { 68 try { return Integer.parseInt(getInitParameter("socketPort")); } 69 catch (NumberFormatException e) { return DEFAULT_PORT; } 70 } 71 72 77 abstract public void handleClient(Socket client); 78 79 84 public void destroy() { 85 try { 86 daemonThread.stop(); 87 daemonThread = null; 88 } 89 catch (Exception e) { 90 log("Problem stopping server socket daemon thread: " + 91 e.getClass().getName() + ": " + e.getMessage()); 92 } 93 } 94 } 95 96 99 class Daemon extends Thread { 100 101 private ServerSocket serverSocket; 102 private DaemonHttpServlet servlet; 103 104 public Daemon(DaemonHttpServlet servlet) { 105 this.servlet = servlet; 106 } 107 108 public void run() { 109 try { 110 serverSocket = new ServerSocket(servlet.getSocketPort()); 112 } 113 catch (Exception e) { 114 servlet.log("Problem establishing server socket: " + 115 e.getClass().getName() + ": " + e.getMessage()); 116 return; 117 } 118 119 try { 120 while (true) { 121 try { 125 servlet.handleClient(serverSocket.accept()); 126 } 127 catch (IOException ioe) { 128 servlet.log("Problem accepting client's socket connection: " + 129 ioe.getClass().getName() + ": " + ioe.getMessage()); 130 } 131 } 132 } 133 catch (ThreadDeath e) { 134 try { 136 serverSocket.close(); 137 } 138 catch (IOException ioe) { 139 servlet.log("Problem closing server socket: " + 140 ioe.getClass().getName() + ": " + ioe.getMessage()); 141 } 142 } 143 } 144 } 145 | Popular Tags |