package uk.ac.cam.em487.fjava.tick4;
import java.net.Socket;
import uk.ac.cam.cl.fjava.messages.Message;
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 client handler for the server. There is one per client connected", ticker = Ticker.D)
public class ClientHandler {
protected Socket socket;
protected MultiQueue<Message> multiQueue;
protected String nickname;
protected MessageQueue<Message> clientMessages;
private Thread receiver;
private Thread sender;
public ClientHandler(Socket s, MultiQueue<Message> q, int nickend) {
socket = s;
multiQueue = q;
nickname = String.format("Anonymous%05d", nickend);
clientMessages = new SafeMessageQueue<Message>();
q.register(clientMessages);
StatusMessage connected = new StatusMessage(String.format(
"%s connected from %s.", nickname, s.getInetAddress()
.getHostName()));
multiQueue.put(connected);
sender = new Thread(new SenderTask(this));
receiver = new Thread(new ReceiverTask(this));
sender.start();
receiver.start();
}
public void disconnect() {
multiQueue.deregister(clientMessages);
StatusMessage goodBye = new StatusMessage(nickname
+ " has disconnected.");
multiQueue.put(goodBye);
}
}