1 36 package org.columba.ristretto.testserver; 37 38 import java.io.IOException ; 39 import java.io.InputStream ; 40 import java.io.OutputStream ; 41 import java.net.ServerSocket ; 42 import java.net.Socket ; 43 44 public class TestServer implements Runnable { 45 46 protected ServerSocket serverSocket; 47 protected Thread thread; 48 protected StringBuffer lineBuffer; 49 protected TestServerSession session; 50 51 protected boolean closeNow; 52 53 public TestServer(int port, TestServerSession session) throws IOException { 54 serverSocket = new ServerSocket (port); 55 closeNow = false; 56 57 this.session = session; 58 59 lineBuffer = new StringBuffer (); 60 61 thread = new Thread (this); 62 thread.setDaemon(false); 63 thread.start(); 64 65 } 66 67 public synchronized void stop() { 68 try { 69 if (serverSocket != null) 70 serverSocket.close(); 71 } catch (Exception ex) { 72 ex.printStackTrace(); 73 } 74 } 75 76 public void run() { 77 try { 78 Socket client = serverSocket.accept(); 80 if (client == null) 81 return; 82 83 String host = client.getLocalAddress().getHostAddress(); 85 if (!(host.equals("127.0.0.1"))) { 86 client.close(); 88 } 89 90 send(client.getOutputStream(), session.serverHelloResponse()); 92 93 while( !session.closeConnection() && !closeNow ) { 94 String clientCommand = readLine(client.getInputStream()); 96 97 String response = session.next(clientCommand); 98 if( response == null ) { 99 stop(); 100 throw new Exception ("No response for " + clientCommand + "-" ); 101 } 102 send(client.getOutputStream(), response); 103 } 104 105 client.close(); 106 107 } catch (Exception ex) { 108 ex.printStackTrace(); 109 stop(); 110 } 111 } 112 113 private String readLine(InputStream in) throws IOException { 114 lineBuffer.delete(0, lineBuffer.length()); 116 117 int read = in.read(); 118 while (read != '\r' && read != -1) { 120 lineBuffer.append((char) read); 121 read = in.read(); 122 } 123 lineBuffer.append((char) read); 124 125 read = in.read(); 127 lineBuffer.append((char) read); 128 129 return lineBuffer.toString(); 130 } 131 132 private void send(OutputStream out, String response) throws IOException { 133 if( response == null || response.length() == 0) return; 134 135 if( response.charAt(response.length()-1) == '\0') { 136 response = response.substring(0,response.length()-1); 137 closeNow = true; 138 } 139 out.write(response.getBytes()); 140 out.flush(); 141 } 142 } 143 | Popular Tags |