| Home >> All >> org >> mtpgsql >> [ server Javadoc ] |
Source code: org/mtpgsql/server/SimpleServer.java
1 package org.mtpgsql.server; 2 3 import java.io.*; 4 import java.net.*; 5 import java.awt.*; 6 import java.awt.event.*; 7 8 public class SimpleServer implements Runnable,ActionListener { 9 public ThreadGroup connections = new ThreadGroup("connections"); 10 11 ServerSocket server_socket = null; 12 boolean running = true; 13 14 public SimpleServer(ServerSocket server) { 15 server_socket = server; 16 } 17 18 public static void main(String[] args) { 19 Button bt = new Button(); 20 try { 21 java.awt.Frame f = new java.awt.Frame(); 22 f.setTitle("Multithreaded Postgres SimpleServer"); 23 f.show(); 24 f.setLayout(new BorderLayout()); 25 bt.setLabel("SHUTDOWN"); 26 f.add(bt,BorderLayout.CENTER); 27 f.validate(); 28 } catch ( Throwable exp ) { 29 System.out.println("no display"); 30 } 31 System.loadLibrary("mtpgjava"); 32 33 try { 34 SimpleServer server = new SimpleServer(new ServerSocket(5432)); 35 server.init(); 36 bt.addActionListener(server); 37 Runtime.getRuntime().addShutdownHook(new Thread(server)); 38 boolean alive = true; 39 40 while ( alive ) { 41 server.connect(); 42 } 43 } catch (IOException ioe) { 44 ioe.printStackTrace(); 45 } 46 } 47 48 public void actionPerformed(ActionEvent ae) 49 { 50 System.exit(0); 51 } 52 53 public void connect() throws IOException 54 { 55 Socket socket = server_socket.accept(); 56 new Thread(connections,new Connection(this,socket)).start(); 57 } 58 59 public static native void init(); 60 public static native void close(); 61 62 public boolean isRunning() 63 { 64 return running; 65 } 66 67 public void run() { 68 running = false; 69 try { 70 server_socket.close(); 71 } catch ( IOException ioe ) { 72 ioe.printStackTrace(); 73 } 74 int count = connections.activeCount(); 75 while ( count > 0 ) { 76 Thread[] stopper = new Thread[count]; 77 connections.enumerate(stopper); 78 for(int x=0;x<count;x++ ) { 79 if ( stopper[x] != null ) { 80 stopper[x].interrupt(); 81 try { 82 stopper[x].join(); 83 } catch ( InterruptedException ie ) { 84 ie.printStackTrace(); 85 } 86 } 87 count = connections.activeCount(); 88 } 89 } 90 close(); 91 } 92 93 }