1 21 package org.jsmtpd.core.receive; 22 23 import java.io.BufferedWriter ; 24 import java.io.IOException ; 25 import java.io.OutputStreamWriter ; 26 import java.net.InetSocketAddress ; 27 import java.net.ServerSocket ; 28 import java.net.Socket ; 29 30 import org.apache.commons.logging.Log; 31 import org.apache.commons.logging.LogFactory; 32 import org.jsmtpd.generic.threadpool.BusyThreadPoolException; 33 import org.jsmtpd.generic.threadpool.GrowingThreadPool; 34 import org.jsmtpd.generic.threadpool.ThreadPool; 35 36 42 public class Receiver extends Thread { 43 44 private ServerSocket sock = null; 45 private ThreadPool p = null; 46 public boolean runing = true; 47 private Log log = LogFactory.getLog(Receiver.class); 48 private Socket inc = null; 49 50 public Receiver(int port, int maxInst) throws IOException , InstantiationException , IllegalAccessException , ClassNotFoundException { 51 p = new GrowingThreadPool(maxInst, "org.jsmtpd.core.receive.ReceiverWorkerImpl","R"); 52 sock = new ServerSocket (port); 53 log.info("Listening for connections on port " + port); 54 this.start(); 55 } 56 57 public void run() { 58 try { 59 while ((inc = sock.accept()) != null) { 60 try { 61 p.assignFreeThread(inc); 62 } catch (BusyThreadPoolException e1) { 63 handleBusy(inc); 64 } 65 } 66 sock.close(); 67 } catch (IOException e) { 68 } 69 log.info("Server is no longer listening for incoming connections"); 70 } 71 72 private void handleBusy(Socket inc) { 73 String remote = ((InetSocketAddress ) inc.getRemoteSocketAddress()).getAddress().getHostAddress(); 74 BufferedWriter wr = null; 75 try { 76 log.error("Unable to serve " + remote + ", replied 421 Service unavaible due to heavy load"); 77 wr = new BufferedWriter (new OutputStreamWriter (inc.getOutputStream())); 78 wr.write("421 Service unavaible due to heavy load"); 79 wr.flush(); 80 81 } catch (IOException e) { 82 log.error(e); 83 } 84 try { 85 wr.close(); 86 } catch (IOException e1) { 87 log.error(e1); 88 } 89 } 90 91 public void shutdown() { 92 try { 93 sock.close(); 94 } catch (IOException e) { 95 } 96 p.forceShutdown(); 97 } 98 } | Popular Tags |