瀏覽代碼

Bugfixing, cleaning, renaming, lastmessage logging

Client now logs messages sent for easy access. Press the up and down
arrow keys to access latest messages.
Renamed a few mthods, commented a few lines.
Added the option to list users in specific channel to the /list command.
Tankernn 10 年之前
父節點
當前提交
cf4e931631

+ 6 - 0
.classpath

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+	<classpathentry kind="output" path="bin"/>
+</classpath>

+ 61 - 22
src/client/ChatWindow.java

@@ -4,8 +4,11 @@ import java.awt.BorderLayout;
 import java.awt.Dimension;
 import java.awt.GridBagConstraints;
 import java.awt.GridBagLayout;
+import java.awt.Point;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
 import java.io.EOFException;
 import java.io.File;
 import java.io.IOException;
@@ -14,6 +17,7 @@ import java.io.PrintWriter;
 import java.net.InetSocketAddress;
 import java.net.Socket;
 import java.net.SocketTimeoutException;
+import java.util.ArrayList;
 
 import javax.swing.*;
 import javax.swing.border.EmptyBorder;
@@ -21,13 +25,13 @@ import javax.swing.border.EmptyBorder;
 import common.Message;
 
 @SuppressWarnings("serial")
-public class ChatWindow extends JFrame implements ActionListener, Runnable{
+public class ChatWindow extends JFrame implements ActionListener, Runnable, KeyListener{
 	Thread getMessages;
 	static File confFile = new File("client.properties");
 	
-	String adress;
-	int port;
-	String username;
+	String adress, username;
+	ArrayList<String> lastMess = new ArrayList<String>();
+	int port, messIndex = 0;
 	
 	Socket so = new Socket();
 	ObjectInputStream objIn;
@@ -44,19 +48,20 @@ public class ChatWindow extends JFrame implements ActionListener, Runnable{
 	
 	Console chat = new Console();
 	JScrollPane scroll = new JScrollPane(chat);
-	JTextField skriv = new JTextField();
+	JTextField write = new JTextField();
 	
 	public ChatWindow(String adress, int port, String username) {
 		this.adress = adress;
 		this.port = port;
 		this.username = username;
 		
+		//List config
 		userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
 		userList.setLayoutOrientation(JList.VERTICAL);
-		
+		//Label config
 		lblUsersOnline.setHorizontalAlignment(JLabel.CENTER);
 		lblUsersOnline.setBorder(new EmptyBorder(5, 5, 5, 5));
-		
+		//Layout config
 		right.setLayout(g);
 		con.fill = GridBagConstraints.HORIZONTAL;
 		con.weightx = 1;
@@ -72,23 +77,24 @@ public class ChatWindow extends JFrame implements ActionListener, Runnable{
 		con.fill = GridBagConstraints.HORIZONTAL;
 		right.add(reconnect, con);
 		
-		reconnect.addActionListener(this);
-		
 		setLayout(new BorderLayout());
-		add(chat, BorderLayout.NORTH); add(skriv, BorderLayout.SOUTH); add(right, BorderLayout.EAST);
+		add(chat, BorderLayout.NORTH); add(write, BorderLayout.SOUTH); add(right, BorderLayout.EAST);
 		
+		//Scrollbar config
 		add(scroll);
 		scroll.setMinimumSize(new Dimension(100, 100));
 		scroll.setViewportView(chat);
 		scroll.setSize(500, 130);
 		
-		skriv.addActionListener(this);
-		chat.setSize(500, 450);
-		chat.setEditable(false);
+		//Listener config
+		reconnect.addActionListener(this);
+		write.addKeyListener(this);
 		
-		setSize(500, 500);
+		//Window config
+		this.setLocation(new Point(100, 100));
+		setSize(600, 600);
 		setVisible(true);
-		setTitle("Chat | Username: " + username);
+		setTitle("Chat on " + adress + " | Username: " + username);
 		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
 		
 		connect(adress, port, username);
@@ -99,7 +105,7 @@ public class ChatWindow extends JFrame implements ActionListener, Runnable{
 			out.println(text);
 		else {
 			chat.log("Not connected to server!");
-			skriv.setEnabled(false);
+			write.setEnabled(false);
 		}
 	}
 	
@@ -136,17 +142,13 @@ public class ChatWindow extends JFrame implements ActionListener, Runnable{
 		getMessages = new Thread(this);
 		getMessages.start();
 		
-		skriv.setEnabled(true);
+		write.setEnabled(true);
 	}
 	
 	@Override
 	public void actionPerformed(ActionEvent e) {
-		if (e.getSource() == skriv) {
-			send(skriv.getText());
-			skriv.setText("");
-		} else if (e.getSource() == reconnect) {
+		if (e.getSource() == reconnect)
 			connect(adress, port, username);
-		}
 	}
 
 	@Override
@@ -178,4 +180,41 @@ public class ChatWindow extends JFrame implements ActionListener, Runnable{
 				chat.log(fromServer.toString());
 		}
 	}
+
+	@Override
+	public void keyPressed(KeyEvent eKey) {
+		int keyCode = eKey.getKeyCode();
+		 switch( keyCode ) {
+	        case KeyEvent.VK_UP:
+	        	if (messIndex > 0)
+	        		messIndex--;
+	        	if (!lastMess.isEmpty())
+	        		write.setText(lastMess.get(messIndex));
+	            break;
+	        case KeyEvent.VK_DOWN:
+	        	if (messIndex <= lastMess.size())
+	        		messIndex++;
+	        	if (messIndex >= lastMess.size()) {
+	        		messIndex = lastMess.size();
+	        		write.setText("");
+	        	} else
+	        		write.setText(lastMess.get(messIndex));
+	            break;
+	        case KeyEvent.VK_ENTER:
+	        	String text = write.getText().trim();
+	    		if (!text.equals("")) {
+	    			send(text);
+	    			lastMess.add(text);
+	    			messIndex = lastMess.size();
+	    			write.setText("");
+	    		}
+	        	break;
+	     }
+	}
+
+	@Override
+	public void keyReleased(KeyEvent arg0) {}
+
+	@Override
+	public void keyTyped(KeyEvent arg0) {}
 }

+ 4 - 0
src/client/Console.java

@@ -10,6 +10,10 @@ import common.Message;
 @SuppressWarnings("serial")
 public class Console extends JTextPane {
 	
+	public Console() {
+		setEditable(false);
+	}
+	
 	void log(String str) {
 		SimpleAttributeSet style = new SimpleAttributeSet();
 		StyleConstants.setForeground(style, Color.RED);

+ 18 - 2
src/command/List.java

@@ -7,7 +7,23 @@ public class List extends Command {
 	
 	@Override
 	public void execute(String[] args, Client caller) {
-		caller.send("Users online are:" + "\n" + Server.getUsersOnlineString());
+		String arr, channelName = null;
+		
+		if (args.length >= 1) {
+			channelName = args[0];
+			try {
+				arr = Server.getChannelByName(channelName).listClients();
+			} catch (NullPointerException ex) {
+				caller.send("No channel named " + channelName + ".");
+				return;
+			}
+		} else
+			arr =  Server.listClients();
+		
+		if (channelName == null)
+			caller.send("Users online are:" + "\n" + arr);
+		else
+			caller.send("Users in channel " + channelName + " are:" + "\n" + arr);
 	}
 
 	@Override
@@ -22,7 +38,7 @@ public class List extends Command {
 
 	@Override
 	public String writeDescription() {
-		return "Lists all users online.";
+		return "Lists all users online. (/list [channel])";
 	}
 
 	@Override

+ 7 - 8
src/command/PrivateMessage.java

@@ -9,16 +9,15 @@ public class PrivateMessage extends Command {
 
 	@Override
 	public void execute(String[] args, Client caller) {
-		Client reciever = null;
-		try {
-			reciever = Server.getUserByName(args[0]);
-		} catch (Exception ex) {
-			caller.send("No such user!");
-			return;
-		}
+		Client reciever = Server.getUserByName(args[0]);
 			
-		if (caller.equals(reciever))
+		if (caller.equals(reciever)) {
+			caller.send("Please don't speak with yourself.");
 			return;
+		} else if (reciever == null) {
+			caller.send("No user called " + args[0] + ".");
+			return;
+		}
 		
 		Message mess = new Message("PM", caller.username, this.stringArrayToString(CommandHandler.removeFirst(args)));
 		

+ 1 - 1
src/server/Client.java

@@ -107,7 +107,7 @@ public class Client implements Runnable, ActionListener {
 		Server.cleanUp();
 		
 		if (output)
-			Server.broadcast(new Message(username + " has disconnected."));
+			Server.wideBroadcast(new Message(username + " has disconnected."));
 	}
 	
 	public void disconnect() {

+ 1 - 0
src/server/CommandHandler.java

@@ -26,6 +26,7 @@ public class CommandHandler {
 							commands[i].execute(removeFirst(command), caller); //Execute command
 						} catch (Exception e) {
 							caller.send("Error while executing command!");
+							e.printStackTrace();
 						} 
 						return;
 					} else {

+ 4 - 4
src/server/Server.java

@@ -61,7 +61,7 @@ public class Server {
 				newClient = new Client(Server.so.accept());
 				clients.add(newClient);
 				channels[0].add(newClient);
-				broadcast(new Message(newClient.username + " has connected."));
+				wideBroadcast(new Message(newClient.username + " has connected."));
 			} catch (IllegalArgumentException ex) {
 				
 			} catch (ArrayIndexOutOfBoundsException ex) {
@@ -84,7 +84,7 @@ public class Server {
 		return null;
 	}
 
-	public static void broadcast(Message mess) {
+	public static void wideBroadcast(Message mess) {
 		clients.broadcast(mess);
 	}
 
@@ -92,7 +92,7 @@ public class Server {
 		return clients.listClientsArray();
 	}
 	
-	public static String getUsersOnlineString() {
+	public static String listClients() {
 		return clients.listClients();
 	}
 
@@ -108,7 +108,7 @@ public class Server {
 	}
 	
 	public static void exit() {
-		broadcast(new Message("Shutting down server!"));
+		wideBroadcast(new Message("Shutting down server!"));
 		
 		for (int i = 0; i < clients.size(); i++)
 			clients.get(i).disconnect();