package uk.ac.cam.em487.fjava.tick2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Date;
import uk.ac.cam.cl.fjava.messages.ChangeNickMessage;
import uk.ac.cam.cl.fjava.messages.ChatMessage;
import uk.ac.cam.cl.fjava.messages.Message;
import uk.ac.cam.em487.fjava.tick2.FurtherJavaPreamble.Ticker;
@FurtherJavaPreamble (
author = "Eduardo Munoz",
date = "2011/11/13",
crsid = "em487",
summary = "Class to implement a thread that is always polling on the command line",
ticker = Ticker.A)
public class SenderTask implements Runnable {
ChatClient client;
String line;
BufferedReader br;
OutputStream os;
ObjectOutputStream oos;
public SenderTask(ChatClient client) {
br = new BufferedReader(new InputStreamReader(System.in));
this.client = client;
try {
os = client.getSocket().getOutputStream();
oos = new ObjectOutputStream(os);
}
catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
while ((line = br.readLine()) != null) {
Message m = createMessage(line);
oos.writeObject(m);
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (ExitApplicationException e) {
return;
}
}
private Message createMessage(String text) throws ExitApplicationException {
Message m = null;
if (text.startsWith("\\")) {
if (text.startsWith("\\nick ")) {
m = new ChangeNickMessage(text.substring(6));
}
else if (text.equals("\\quit")) {
ChatClient.printMessage(new Date(), "Client",
"Connection terminated");
throw new ExitApplicationException();
}
else {
String toSend = String.format("Unknown command \"%s\".", text
.substring(1));
ChatClient.printMessage(new Date(), "Client", toSend);
}
}
else {
m = new ChatMessage(text);
}
return m;
}
}