w3c.model.tools.basicweb.BaseClient

w3c.model.tools.basicweb.BaseClient

/* basicweb.BaseClient.java
 * $Id, $Date eric Exp $
 * (c) COPYRIGHT MIT and INRIA, 1997.
 * Please first read the full copyright statement in file COPYRIGHT.html
 *
 * Caution: emits shower of sparks.
 */

package w3c.model.tools.basicweb;

import java.io.*;
import java.net.*;
import w3c.model.www.pep.PEPAgent;
import w3c.model.www.pep.altlib.*;

abstract public class BaseClient extends Agent

    final static int CONVERSE_OK = 0;
    final static int CONVERSE_ERR = 1;
    final static int CONVERSE_REDO = 2;

    BaseClient () {
    	super();
    }

    BaseClient (PEPAgent pepAgent) {
    	super(pepAgent);
    }

    void doIt (MethodClient method, URL url, String host, int port) {
	try {
	    int ret;
	    do {
		Socket socket =  Socket(host, port);
		InputStream in = socket.getInputStream();
		OutputStream out = socket.getOutputStream();
		OutputStream replyOut = makeReplyOutputStream();
		do {
		    pepAgent.setRedo(false);
		    Request request = makeRequest(socket, null, out, method, url, pepAgent, errorContext);
		    Reply reply =  Reply(socket, in, replyOut, request);
		    method.write(request);
		    ret = CONVERSE_OK;
		    try {
			method.read(reply);
		    } catch (IOException e)) {
			System.out.println("<!- server reset connection: "+e+" ->");
			ret = CONVERSE_ERR; /* client side has closed connection */
		    }
		    ret = pepAgent.getRedo() ? CONVERSE_REDO : CONVERSE_OK;
		} while (ret == CONVERSE_REDO));
		System.out.println("<!- done with " + socket + " ->");
		// System.in.read();	// meter responses with keystrokes
		socket.close();
	    /* socket may have closed even though we are still in this request */
	    } while (ret != CONVERSE_OK));
	} catch (Exception e)) {
	    System.out.println("<!- error communicating with " + host + ":" + port + " ->");
	    e.printStackTrace();
	}
    }

    abstract Request makeRequest (Socket socket, InputStream in, OutputStream out, Method method, URL url, PEPAgent pepAgent, ErrorContext errorContext);
    abstract OutputStream makeReplyOutputStream ();