/////// CgiSocket.java /////// import java.io.*; import java.net.*; // The msg to send is assumed to be correctly encoded // and formatted already public class CgiSocket implements CgiClient { public CgiSocket(String server, int port, String cg) { try { host = server; cgi = cg; sin = new Socket(host, port); if ( sin == null ) System.err.println("socket failed"); out = new PrintWriter(sin.getOutputStream()); ins = sin.getInputStream(); } catch (UnknownHostException e) { JavaSystem.error(e); } catch (IOException e) { JavaSystem.error(e); } } protected CgiSocket() {} /* posts the query msg, sets up input streams */ /* This method can be called only once */ public void postQuery(String msg) { if (out != null) { postHeader(msg); // header out.println(msg); out.flush(); // msg body } } public TextLines textResponse() { if ( ins != null ) { TextLines from = new TextLines(); int len = from.input(ins); close(); if ( len > -1 ) return from; } return null; } public void close() { try { if ( sin != null ) sin.close(); } catch (IOException e) { JavaSystem.error(e); } } public String readNextLine() { try { if ( in == null ) in = new BufferedReader (new InputStreamReader(ins)); return in.readLine(); } catch (IOException e) { JavaSystem.error(e); } return null; } public InputStream getInputStream() { return ins; } protected void postHeader(String msg) { out.print("POST " + cgi + " HTTP/1.1\r\n"); // request out.print("HOST: " + host + "\r\n"); // host out.print("User-Agent: JavaCgiSocket\r\n"); // agent out.print("Content-Type: application/x-www-form-urlencoded\r\n"); out.print("Content-Length: " + msg.length() + "\r\n"); out.print("\r\n"); // empty line } protected Socket sin; protected BufferedReader in; protected InputStream ins; protected PrintWriter out; protected String host; protected String cgi; }