import java.io.*; import java.net.Socket; /** * Ip 4.1.2 * @author emi-lind * * Controls a client */ public class ClientHandler implements Runnable { private boolean _alive; private BufferedReader _clientInput; private PrintWriter _clientOutput; private ChatServer _server; private Socket _connection; /** * A thread that handles a connection to one client. * @param aServer the server * @param aConnection the socket assigned to the client */ public ClientHandler(ChatServer aServer, Socket aConnection) { if (aConnection == null || aServer == null) { throw new IllegalArgumentException(); } _server = aServer; try { _clientInput = new BufferedReader(new InputStreamReader(aConnection.getInputStream())); _clientOutput = new PrintWriter(new OutputStreamWriter(aConnection.getOutputStream(), "ISO-8859-1"), true); _connection = aConnection; _alive = true; Thread t = new Thread(this); t.start(); } catch (IOException e) { _server.showMessage(e.toString(), true); } } @Override public void run() { try { String readed; while ((readed = _clientInput.readLine()) != null && this._alive) { _server.broadcastMessageToAllClients(readed); ClientHandler.this._server.showMessage(_connection.getInetAddress().getHostAddress() + ": " + readed, false); } // If we get here, the client disconnected. _clientInput.close(); _clientOutput.close(); _connection.close(); } catch (IOException e){} _server.killClientHandler(this); } /** * Kills the thread */ public void killThread() { this._alive = false; } /** * Sends a message to this client * @param aMessage the message */ public void sendMessage(String aMessage) { _clientOutput.println(aMessage); } }