package dcj.examples.messageV2;
import java.util.Vector;
import java.lang.*;
import java.io.*;
abstract class BasicMsgHandler implements Runnable
{
// Static message handler for applications where only one is used
// and needs to be globally accessible.
public static BasicMsgHandler current = null;
InputStream msgIn;
OutputStream msgOut;
StreamTokenizer tokenizer;
public BasicMsgHandler(InputStream in, OutputStream out) {
setStreams(in, out);
current = this;
}
protected void setStreams(InputStream in, OutputStream out) {
msgIn = in;
msgOut = out;
}
public BasicMessage readMsg() throws IOException {
BasicMessage msg;
String token;
DataInputStream din = new DataInputStream(msgIn);
// Get message ID and build corresponding BasicMessage
token = din.readUTF();
msg = buildMessage(token);
// Tell message to read its args
if (msg != null && msg.readArgs(msgIn))
return msg;
else
return null;
}
public void sendMsg(BasicMessage msg) throws IOException {
boolean success = true;
DataOutputStream dout = new DataOutputStream(msgOut);
// Send message ID
dout.writeUTF(msg.messageID());
// Tell message to send its arguments
msg.writeArgs(msgOut);
}
public void run() {
try {
while (true) {
BasicMessage 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 abstract BasicMessage buildMessage(String msgId);
}
|