FileDocCategorySizeDatePackage
SimpleAgent.javaAPI DocExample2652Sun Oct 31 16:09:16 GMT 1999dcj.examples.security

SimpleAgent

public class SimpleAgent extends Thread
Source code from "Java Distributed Computing", by Jim Farley. Class: SimpleAgent Example: 5-1 Description: An agent that simply opens a socket to a remote agent and exchanges text messages with it.

Fields Summary
protected Socket
serverConn
protected InputStream
inStream
protected OutputStream
outStream
Vector
msgQueue
Constructors Summary
public SimpleAgent(String host, int port)

    try {
      serverConn = new Socket(host, port);
    }
    catch (UnknownHostException e) {
      throw new IllegalArgumentException("Bad host name given.");
    }
    catch (IOException e) {
      System.out.println("SimpleAgent: " + e);
      System.exit(1);
    }

    try {
      inStream = new DataInputStream(serverConn.getInputStream());
      outStream = new DataOutputStream(serverConn.getOutputStream());
    }
    catch (Exception e) {
      inStream = null;
      outStream = null;
    }
  
Methods Summary
public synchronized voidaddMsg(java.lang.String msg)

    msgQueue.addElement(msg);
  
protected voidcloseConnection()

    try {
      serverConn.close();
    }
    catch (Exception e) {}
    inStream = null;
    outStream = null;
  
protected synchronized java.lang.StringnextMsg()

    String msg = null;
    if (msgQueue.size() > 0) {
      msg = (String)msgQueue.elementAt(0);
      msgQueue.removeElementAt(0);
    }
    return msg;
  
protected voidprocessMsg(java.lang.String msg)

public voidrun()

    // Go into infinite loop, sending messages, receiving responses and
    // processing them...
    DataInputStream din = (inStream instanceof DataInputStream ?
			   (DataInputStream)inStream :
			   new DataInputStream(inStream));
    DataOutputStream dout = (outStream instanceof DataOutputStream ?
			     (DataOutputStream)outStream :
			     new DataOutputStream(outStream));
    while (true) {
      String msg = nextMsg();
      if (msg != null) {
        String inMsg = "", inToken = "";
        try {
          dout.writeUTF(msg);
          while (inToken.compareTo("END") != 0) {
            inToken = din.readUTF();
            inMsg = inMsg + " " + inToken;
          }
          processMsg(inMsg);
        }
        catch (Exception e) {}
      }
    }