package dcj.examples.security;
import java.lang.*;
import java.net.*;
import java.io.*;
import java.util.Vector;
/**
* 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.
*/
public class SimpleAgent extends Thread {
// Our socket connection to the server
protected Socket serverConn;
// The input/output streams from the other agent
protected InputStream inStream;
protected OutputStream outStream;
// Message queue
Vector msgQueue;
public SimpleAgent(String host, int port)
throws IllegalArgumentException {
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;
}
}
public synchronized void addMsg(String msg) {
msgQueue.addElement(msg);
}
protected synchronized String nextMsg() {
String msg = null;
if (msgQueue.size() > 0) {
msg = (String)msgQueue.elementAt(0);
msgQueue.removeElementAt(0);
}
return msg;
}
// Close the connection to the server, when finished.
protected void closeConnection() {
try {
serverConn.close();
}
catch (Exception e) {}
inStream = null;
outStream = null;
}
public void run() {
// Go into infinite loop, sending messages, receiving responses and
// processing them...
DataInputStream din = (DataInputStream)inStream;
DataOutputStream dout = (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) {}
}
}
}
protected void processMsg(String msg) {}
} |