1 14 15 package xmladder; 16 17 import java.net.*; 18 import java.io.*; 19 import org.quickserver.net.server.ClientCommandHandler; 20 import org.quickserver.net.server.ClientEventHandler; 21 import org.quickserver.net.server.ClientHandler; 22 import org.quickserver.net.server.DataMode; 23 import org.quickserver.net.server.DataType; 24 import java.util.logging.*; 25 26 public class CommandHandler implements ClientEventHandler, ClientCommandHandler { 27 private static Logger logger = Logger.getLogger( 28 CommandHandler.class.getName()); 29 30 private final static String welcome = "<welcome name=\"XmlAdder v1.0\">"+ 31 "\n"+"<note>Send <quit /> to close connection</note>"; 32 33 public void gotConnected(ClientHandler handler) 35 throws SocketTimeoutException, IOException { 36 logger.fine("Connection opened : "+handler.getHostAddress()); 37 42 handler.sendClientBytes(welcome); 43 } 44 45 public void lostConnection(ClientHandler handler) 46 throws IOException { 47 logger.fine("Connection lost : "+handler.getHostAddress()); 48 } 49 public void closingConnection(ClientHandler handler) 50 throws IOException { 51 handler.sendSystemMsg("Connection closed: "+handler.getHostAddress(), Level.FINE); 52 } 53 55 public void handleCommand(ClientHandler handler, String command) 56 throws SocketTimeoutException, IOException { 57 AddNumberReq addNumberReq = null; 58 AddNumberRes addNumberRes = new AddNumberRes(); 59 command = command.trim(); 60 try { 61 if(command.equals("<quit />")) { 62 handler.sendClientBytes("<bye />"); 63 handler.closeConnection(); 64 return; 65 } 66 67 Data data = (Data)handler.getClientData(); 68 data.addXmlPart(command); 69 70 String xmlToProcess = null; 71 while(true) { 72 xmlToProcess = data.getNextXML(); 73 if(xmlToProcess==null) 74 break; 75 76 logger.fine("Got xml to process from data \n:"+xmlToProcess); 77 78 addNumberReq = AddNumberReq.fromXML(xmlToProcess); 79 if(addNumberReq==null) { 80 addNumberRes.setType("error"); 81 addNumberRes.setValue("Bad XML Got!"); 82 } 83 84 int a = addNumberReq.getNumberA(); 85 int b = addNumberReq.getNumberB(); 86 int c = a + b; 87 88 addNumberRes.setType("sum"); 89 addNumberRes.setValue(""+c); 90 handler.sendClientBytes(addNumberRes.toXML()); 91 } 92 } catch(IOException e) { 93 throw e; 94 } catch(Exception e) { 95 addNumberRes.setType("error"); 96 addNumberRes.setValue("Exception : "+e); 97 handler.sendClientBytes(addNumberRes.toXML()); 98 } 99 } 100 } 101 | Popular Tags |