1 4 package chipchat; 5 6 import java.io.BufferedReader ; 7 import java.io.IOException ; 8 import java.io.InputStream ; 9 import java.io.InputStreamReader ; 10 import java.io.OutputStream ; 11 import java.net.ServerSocket ; 12 import java.net.Socket ; 13 import java.util.HashMap ; 14 15 19 public class Server extends Thread { 20 public static Server instance = null; 21 22 private int serverPort = 6543; 23 private boolean useServer = false; 24 25 private Server() { 26 try { 27 serverPort = 28 Integer.parseInt(Env.getInstance().getProperty("Server.port")); 29 } catch (NumberFormatException e) { 30 e.printStackTrace(); 31 } 32 useServer = 33 "true".equalsIgnoreCase( 34 Env.getInstance().getProperty("Server.listen")); 35 36 if (useServer) { 37 this.setDaemon(true); 38 this.start(); 39 } 40 } 41 42 public static void initialize() { 43 if (instance == null) { 44 instance = new Server(); 45 } 46 } 47 48 public static int getServerPort() { 49 if (instance == null) { 50 initialize(); 51 } 52 return instance.serverPort; 53 } 54 55 public static boolean isUseServer() { 56 if (instance == null) { 57 initialize(); 58 } 59 return instance.useServer; 60 } 61 62 public void run() { 63 64 final ServerSocket serverSocket; 65 try { 66 serverSocket = new ServerSocket (serverPort); 67 } catch (IOException e) { 68 System.out.println("Server Socket Create Exception... : " + e); 69 e.printStackTrace(); 70 return; 71 } 72 73 while (true) { 74 try { 75 Thread t = new Thread () { 76 Socket client_connection = serverSocket.accept(); 77 public void run() { 78 try { 79 InputStream input = 80 client_connection.getInputStream(); 81 OutputStream output = 82 client_connection.getOutputStream(); 83 BufferedReader rd = 84 new BufferedReader ( 85 new InputStreamReader (input)); 86 String line = rd.readLine(); 87 HashMap header = new HashMap (); 88 do { 89 line = rd.readLine(); 90 if (line.length() == 0) { 91 break; 92 } 93 int idx = line.indexOf(":"); 94 if (idx >= 0) { 95 String name = line.substring(0, idx).trim(); 96 String value = 97 line.substring(idx + 1).trim(); 98 header.put(name, value); 99 } else { 100 System.err.println( 101 "Unknown header : " + line); 102 } 103 } while (true); 104 String inum = (String ) header.get("INUM"); 105 String address = 106 client_connection 107 .getInetAddress() 108 .getHostAddress(); 109 Communicator c = new Communicator(); 110 c.service(address + inum, input, output); 111 } catch (IOException e) { 112 e.printStackTrace(); 113 } finally { 114 if (client_connection != null) { 115 try { 116 client_connection.close(); 117 } catch (IOException e1) { 118 e1.printStackTrace(); 119 } 120 } 121 } 122 } 123 }; 124 t.setDaemon(true); 125 t.start(); 126 } catch (IOException e) { 127 System.out.println("Client IO Exception... : " + e); 128 e.printStackTrace(); 129 } 130 } 131 } 132 } 133 | Popular Tags |