1 package org.myoodb.core; 25 26 import java.io.*; 27 import java.net.*; 28 import java.util.*; 29 import javax.net.ssl.*; 30 31 public abstract class AbstractServer extends HashSet 32 { 33 private Thread m_acceptThread; 34 private ThreadGroup m_threadGroup; 35 36 protected Acceptor m_acceptor; 37 protected ServerSocket m_serverSocket; 38 39 public AbstractServer(int port, boolean secure) throws IOException 40 { 41 if (secure == true) 42 { 43 SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); 44 m_serverSocket = (ServerSocket) sslserversocketfactory.createServerSocket(port); 45 } 46 else 47 { 48 m_serverSocket = new ServerSocket(port); 49 } 50 51 m_serverSocket.setReuseAddress(true); 52 53 m_acceptor = new Acceptor(this); 54 m_threadGroup = new ThreadGroup (getClass().getName()); 55 m_acceptThread = newThread(m_acceptor); 56 } 57 58 public ThreadGroup getThreadGroup() 59 { 60 return m_threadGroup; 61 } 62 63 public Thread newThread(Runnable run) 64 { 65 return new Thread (getThreadGroup(), run); 66 } 67 68 public synchronized void accept() 69 { 70 if (m_acceptThread.isAlive() == false) 71 { 72 m_acceptThread.start(); 73 } 74 } 75 76 public synchronized void close() throws IOException 77 { 78 Iterator iter = iterator(); 79 while (iter.hasNext()) 80 { 81 ((AbstractClient)iter.next()).close(); 82 } 83 84 m_serverSocket.close(); 85 } 86 87 public synchronized void removeClient(AbstractClient client) 88 { 89 Iterator iter = iterator(); 90 while (iter.hasNext()) 91 { 92 AbstractClient tmpClient = (AbstractClient) iter.next(); 93 94 if (tmpClient == client) 95 { 96 iter.remove(); 97 98 try 99 { 100 tmpClient.close(); 101 } 102 catch (IOException e) 103 { 104 } 105 106 return; 107 } 108 } 109 110 throw new org.myoodb.exception.InternalException("AbstractServer.removeClient (no such client)"); 111 } 112 113 public abstract AbstractClient newClient(Socket socket); 114 115 public abstract Object processWork(AbstractClient client, Object work); 116 117 public abstract void handleException(AbstractClient client, Exception e); 118 119 class Acceptor implements Runnable 120 { 121 protected AbstractServer m_server; 122 123 protected Acceptor(AbstractServer server) 124 { 125 m_server = server; 126 } 127 128 public void run() 129 { 130 try 131 { 132 while (true) 133 { 134 AbstractClient client = m_server.newClient(m_server.m_serverSocket.accept()); 135 if (client != null) 136 { 137 m_server.add(client); 138 client.listen(); 139 } 140 } 141 } 142 catch (Exception e) 143 { 144 } 146 } 147 } 148 } 149 | Popular Tags |