Package uk.ac.cam.em487.fjava.tick5

Source Code of uk.ac.cam.em487.fjava.tick5.ClientHandler

package uk.ac.cam.em487.fjava.tick5;

import java.net.Socket;
import java.sql.SQLException;

import uk.ac.cam.cl.fjava.messages.Message;
import uk.ac.cam.cl.fjava.messages.StatusMessage;
import uk.ac.cam.em487.fjava.tick5.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;
    protected Database database;

    public ClientHandler(Socket s, MultiQueue<Message> q, int nickend, Database database) {
        socket = s;
        multiQueue = q;
        nickname = String.format("Anonymous%05d", nickend);
        clientMessages = new SafeMessageQueue<Message>();
        this.database = database;

        try {
            database.incrementLogins();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        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);
    }
}
TOP

Related Classes of uk.ac.cam.em487.fjava.tick5.ClientHandler

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.