package dcj.examples.messageV2;
import java.lang.*;
import java.io.*;
import java.net.*;
abstract class BasicMsgHandler implements Runnable {
InputStream msgIn;
OutputStream msgOut;
StreamTokenizer tokenizer;
String msgEndToken;
String tokenDelim;
static BasicMsgHandler current = null;
public BasicMsgHandler(InputStream in, OutputStream out,
String endToken,
String delim) {
msgEndToken = endToken;
tokenDelim = delim;
setStreams(in, out);
}
protected void setStreams(InputStream in, OutputStream out) {
msgIn = in;
msgOut = out;
// Wrap the input stream with a tokenizer
tokenizer = new StreamTokenizer(msgIn);
// Set the token delimiting characters on the tokenizer
int len = tokenDelim.length();
for (int i = 0; i < len; i++)
tokenizer.whitespaceChars(tokenDelim.charAt(i), tokenDelim.charAt(i));
}
public BasicMessage readMsg() throws IOException {
BasicMessage msg;
if (tokenizer.nextToken() == StreamTokenizer.TT_WORD) {
String msgId = tokenizer.sval;
msg = buildMessage(msgId);
if (msg.readArgs(msgIn)) {
return msg;
}
else {
msg = null;
}
}
else {
return null;
}
return msg;
}
public void sendMsg(BasicMessage msg) throws IOException {
boolean success = true;
DataOutputStream dout = new DataOutputStream(msgOut);
char delim = tokenDelim.charAt(0);
dout.writeUTF(msg.messageID());
msg.writeArgs(msgOut);
}
public void run() {
try {
while (true) {
BasicMessage msg = readMsg();
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);
}
|