package uk.ac.cam.em487.fjava.tick4;
import java.io.IOException;
import java.io.ObjectInputStream;
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.cl.fjava.messages.RelayMessage;
import uk.ac.cam.cl.fjava.messages.StatusMessage;
import uk.ac.cam.em487.fjava.tick4.FurtherJavaPreamble.Ticker;
@FurtherJavaPreamble(author = "Eduardo Munoz", date = "2011/11/19", crsid = "em487", summary = "Class to implement a thread that gets messages from chat clients", ticker = Ticker.D)
public class ReceiverTask implements Runnable {
ClientHandler cHandler;
ObjectInputStream objectIS;
public ReceiverTask(ClientHandler cHandler) {
this.cHandler = cHandler;
try {
objectIS = new ObjectInputStream(cHandler.socket.getInputStream());
}
catch (IOException e1) {
e1.printStackTrace();
}
}
@Override
public void run() {
while (true) {
Message mesIn = null;
try {
mesIn = (Message) objectIS.readObject();
}
catch (IOException e) {
cHandler.disconnect();
return;
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
Message mesOut = null;
if (mesIn instanceof ChangeNickMessage) {
String oldnickname = cHandler.nickname;
cHandler.nickname = ((ChangeNickMessage) mesIn).name;
mesOut = new StatusMessage(oldnickname + "is now known as "
+ cHandler.nickname);
}
else if (mesIn instanceof ChatMessage) {
mesOut = new RelayMessage(cHandler.nickname,
(ChatMessage) mesIn);
}
if (mesOut != null) {
cHandler.multiQueue.put(mesOut);
}
}
}
}