package dcj.util.message;
import java.util.Vector;
import java.io.*;
/**
* Source code from "Java Distributed Computing", by Jim Farley.
*
* Class: MessageHandler
* Example: 6-10
* Description: The final version of the basic message handler.
*/
public class MessageHandler implements Runnable
{
// A global MessageHandler, for applications where one central
// handler is used.
public static MessageHandler current = null;
InputStream msgIn;
OutputStream msgOut;
Vector msgPrototypes;
public MessageHandler() {}
public MessageHandler(InputStream in, OutputStream out) {
setStreams(in, out);
}
public void setStreams(InputStream in, OutputStream out) {
msgIn = in;
msgOut = out;
}
public void addMessageType(Message prototype) {
msgPrototypes.addElement(prototype);
}
public Message readMsg() throws IOException {
Message msg = null;
DataInputStream din = new DataInputStream(msgIn);
String msgId = din.readUTF();
msg = buildMessage(msgId);
if (msg != null && msg.readArgs(msgIn)) {
return msg;
}
else {
return null;
}
}
public void sendMsg(Message msg) throws IOException {
boolean success = true;
DataOutputStream dout = new DataOutputStream(msgOut);
dout.writeUTF(msg.messageID());
msg.writeArgs(msgOut);
}
public void run() {
try {
while (true) {
Message msg = readMsg();
if (msg != null) {
msg.Do();
}
}
}
// Treat an IOException as a termination of the message
// exchange, and let this message-processing thread die.
catch (IOException e) {}
}
protected Message buildMessage(String msgId) {
Message msg = null;
int numMTypes = msgPrototypes.size();
for (int i = 0; i < numMTypes; i++) {
Message m = (Message)msgPrototypes.elementAt(i);
if (m.handles(msgId)) {
msg = m.newCopy();
break;
}
}
return msg;
}
}
|