package uk.ac.cam.em487.fjava.tick5;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.sql.SQLException;
import uk.ac.cam.cl.fjava.messages.Message;
import uk.ac.cam.cl.fjava.messages.RelayMessage;
import uk.ac.cam.em487.fjava.tick5.FurtherJavaPreamble.Ticker;
@FurtherJavaPreamble(author = "Eduardo Munoz", date = "2011/11/19", crsid = "em487", summary = "Class to implement a thread that sends messages to chat clients", ticker = Ticker.D)
public class SenderTask implements Runnable {
ClientHandler cHandler;
ObjectOutputStream objectOS;
public SenderTask(ClientHandler cHandler) {
this.cHandler = cHandler;
try {
objectOS = new ObjectOutputStream(cHandler.socket.getOutputStream());
}
catch (IOException e1) {
e1.printStackTrace();
}
}
@Override
public void run() {
try {
for (RelayMessage rm: cHandler.database.getRecent()) {
objectOS.writeObject(rm);
}
objectOS.flush();
}
catch (SQLException e1) {
e1.printStackTrace();
}
catch (IOException e) {
System.out.println("IOexception from sender.");
e.printStackTrace();
}
while (true) {
Message mesOut = cHandler.clientMessages.take();
try {
objectOS.writeObject(mesOut);
objectOS.flush();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("IOexception from sender.");
cHandler.disconnect();
return;
}
}
}
}