All pastes #432445 Raw Edit

Stuff

public text v1 · immutable
·published 2007-04-10 07:39 UTC
rendered paste body
import java.net.*;
import java.io.*;

public class ChatServerHandler extends Thread
{
	private Socket client_socket;
	private String client_address;
	private int port;

	private ChatGroup chat_group;

	public ChatServerHandler(Socket socket, ChatGroup chat_group)
	{
		this.chat_group = chat_group;
		client_socket = socket;
		client_address = client_socket.getInetAddress().getHostAddress();
		port = client_socket.getPort();
		System.out.println("Client connection from (" + client_address + ", " + port + ")");
	}

	public void run()
	{
		try
		{
			BufferedReader in  = new BufferedReader(new InputStreamReader( client_socket.getInputStream()));
			PrintWriter out = new PrintWriter( client_socket.getOutputStream(), true );
			
			chat_group.addPerson(client_address, port, out);

			processClient(in, out);

			chat_group.delPerson(client_address, port);
			
			client_socket.close();
		
			System.out.println("Client (" + client_address + ", " + port + ") connection closed\n");
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}

	private void processClient(BufferedReader in, PrintWriter out)
	{
		String line;
		boolean done = false;
		try
		{
			while (!done)
			{
				if((line = in.readLine()) == null)
				{
					done = true;
				}
				else
				{
					System.out.println("Client (" + client_address + ", " + port + "): " + line);
					if (line.trim().equals("bye"))
					{
						done = true;
					}
					else
					{
						doRequest(line, out);
					}
				}
			}
		}
		catch(IOException e)
		{
			System.out.println(e);
		}
	}

	private void doRequest(String line, PrintWriter out)
	{
		if (line.trim().toLowerCase().equals("who"))
		{
			System.out.println("Processing 'who'");
			out.println( chat_group.who() );
		}
		else
		{
			chat_group.broadcast( "("+client_address+", "+port+"): " + line);
		}
	}
}