Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.KeyAdapter;
- import java.awt.event.KeyEvent;
- import java.io.DataOutputStream;
- import java.io.BufferedInputStream;
- import java.io.DataInputStream;
- import java.io.IOException;
- import java.net.Socket;
- import java.util.*;
- import static java.lang.System.exit;
- class ClientGUI extends JFrame implements ActionListener{
- //GUI Objects
- private final JButton bLogout, bSend, bHelp, existButton, newButton, logInButton, registerButton;
- private final JTextField userField, passField, regUserField, regPassField, confirmField;
- private final JFrame logInWindow, existingUserWindow, newUserWindow;
- private final JTextArea messageBox, chatBox, usersList;
- private final JScrollPane chatPane, messagePane, usersPane;
- private ClientInputThread inputThread;
- private DataOutputStream output;
- private Set<String> onlineUsers;
- //Constructor
- public ClientGUI() {
- this.onlineUsers = new HashSet<>();
- //Instantiate objects
- this.bLogout = new JButton("Log Out");
- this.bSend = new JButton("Send");
- this.bHelp = new JButton("Help");
- this.messageBox = new JTextArea(5, 81);
- this.chatBox = new JTextArea(25, 81);
- this.usersList = new JTextArea(25, 18);
- this.bSend.setPreferredSize(new Dimension(200, 100));
- this.messageBox.setBorder(new JTextField().getBorder());
- this.messageBox.setLineWrap(true);
- this.messageBox.addKeyListener(new KeyAdapter(){
- @Override
- public void keyReleased(KeyEvent ev) {
- if(ev.getKeyCode() == KeyEvent.VK_ENTER) {
- actionPerformed(new ActionEvent(bSend, 0, ""));
- }
- }
- });
- this.chatBox.setBorder(new JTextField().getBorder());
- this.chatBox.setLineWrap(true);
- this.chatBox.setEditable(false);
- this.usersList.setBorder(new JTextField().getBorder());
- this.usersList.setLineWrap(false);
- this.usersList.setEditable(false);
- //Set up scroll panes
- this.chatPane = new JScrollPane(this.chatBox);
- this.usersPane = new JScrollPane(this.usersList);
- this.messagePane = new JScrollPane(this.messageBox);
- //Set up main window
- this.setLayout(new GridBagLayout());
- GridBagConstraints c = new GridBagConstraints();
- JPanel buttonPanel = new JPanel(new GridBagLayout());
- c.gridx = 0;
- c.gridy = 0;
- c.fill = GridBagConstraints.HORIZONTAL;
- c.anchor = GridBagConstraints.FIRST_LINE_START;
- buttonPanel.add(this.bHelp, c);
- c.gridx = 1;
- c.gridy = 0;
- c.anchor = GridBagConstraints.FIRST_LINE_START;
- buttonPanel.add(this.bLogout, c);
- c.gridx = 2;
- c.gridy = 0;
- c.insets = new Insets(10, 770, 0, 135);
- c.fill = GridBagConstraints.NONE;
- c.anchor = GridBagConstraints.FIRST_LINE_END;
- buttonPanel.add(new JLabel("Online Users"), c);
- c.insets = new Insets(0, 0 , 0 , 0);
- c.gridx = 0;
- c.gridy = 0;
- this.add(buttonPanel, c);
- JPanel messagePanel = new JPanel(new FlowLayout());
- messagePanel.add(chatPane);
- messagePanel.add(usersPane);
- c.gridx = 0;
- c.gridy = 1;
- this.add(messagePanel, c);
- JPanel bottomPanel = new JPanel(new GridBagLayout());
- c = new GridBagConstraints();
- c.gridx = 0;
- c.gridy = 0;
- bottomPanel.add(messagePane, c);
- c.gridx = 1;
- c.gridy = 0;
- c.insets = new Insets(0, 7, 0, 3);
- bottomPanel.add(this.bSend, c);
- c.gridx = 0;
- c.gridy = 2;
- this.add(bottomPanel, c);
- //Make window invisible until user logs in
- this.getRootPane().setDefaultButton(this.bSend);
- this.setTitle("CSE3461 Chat");
- this.setResizable(false);
- this.setLocationRelativeTo(null);
- this.pack();
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- this.setVisible(false);
- //Create log in or register window
- this.logInWindow = new JFrame();
- this.logInWindow.setTitle("Log In or Register");
- this.logInWindow.setResizable(false);
- this.logInWindow.setPreferredSize(new Dimension(290, 125));
- JPanel logInPanel = new JPanel(new GridLayout(2, 2));
- JLabel existing = new JLabel("Existing Users");
- JLabel newU = new JLabel("New Users");
- existing.setHorizontalAlignment(JLabel.CENTER);
- newU.setHorizontalAlignment(JLabel.CENTER);
- logInPanel.add(existing);
- logInPanel.add(newU);
- this.existButton = new JButton("Log In");
- this.newButton = new JButton("Register");
- this.existButton.addActionListener(this);
- this.newButton.addActionListener(this);
- logInPanel.add(this.existButton);
- logInPanel.add(this.newButton);
- this.logInWindow.add(logInPanel);
- //Set up action listeners
- this.bHelp.addActionListener(this);
- this.bLogout.addActionListener(this);
- this.bSend.addActionListener(this);
- this.logInWindow.pack();
- this.logInWindow.setLocationRelativeTo(null);
- this.logInWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- this.logInWindow.setVisible(true);
- //Create username entry window
- this.existingUserWindow = new JFrame();
- this.existingUserWindow.setTitle("Log In");
- this.existingUserWindow.setResizable(false);
- this.existingUserWindow.setPreferredSize(new Dimension(250, 200));
- JPanel existingUserPanel = new JPanel(new GridLayout(5, 1));
- JLabel userLabel = new JLabel("User Name:");
- JLabel passLabel = new JLabel("Password:");
- this.userField = new JTextField();
- this.passField = new JPasswordField();
- this.logInButton = new JButton("Log In");
- existingUserPanel.add(userLabel);
- existingUserPanel.add(this.userField);
- existingUserPanel.add(passLabel);
- existingUserPanel.add(this.passField);
- existingUserPanel.add(this.logInButton);
- this.logInButton.addActionListener(this);
- this.existingUserWindow.add(existingUserPanel);
- this.existingUserWindow.getRootPane().setDefaultButton(this.logInButton);
- this.existingUserWindow.pack();
- this.existingUserWindow.setLocationRelativeTo(null);
- this.existingUserWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //Create register user window
- this.newUserWindow = new JFrame();
- this.newUserWindow.setTitle("Register User");
- this.newUserWindow.setResizable(false);
- this.newUserWindow.setPreferredSize(new Dimension(275, 250));
- JPanel newUserPanel = new JPanel(new GridLayout(7, 1));
- userLabel = new JLabel("User Name:");
- passLabel = new JLabel("Password:");
- this.regUserField = new JTextField();
- this.regPassField = new JPasswordField();
- this.registerButton = new JButton("Register");
- JLabel confirmLabel = new JLabel("Confirm Password:");
- this.confirmField = new JPasswordField();
- newUserPanel.add(userLabel);
- newUserPanel.add(this.regUserField);
- newUserPanel.add(passLabel);
- newUserPanel.add(this.regPassField);
- newUserPanel.add(confirmLabel);
- newUserPanel.add(this.confirmField);
- newUserPanel.add(this.registerButton);
- this.registerButton.addActionListener(this);
- this.newUserWindow.add(newUserPanel);
- this.newUserWindow.getRootPane().setDefaultButton(this.registerButton);
- this.newUserWindow.pack();
- this.newUserWindow.setLocationRelativeTo(null);
- this.newUserWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- }
- @Override
- public void actionPerformed(ActionEvent e) {
- Object source = e.getSource();
- if (source == this.existButton) {
- try {
- this.output.writeUTF("1");
- } catch (IOException ex) {
- ex.printStackTrace();
- exit(1);
- }
- this.logInWindow.setVisible(false);
- this.existingUserWindow.setVisible(true);
- } else if (source == this.newButton) {
- try {
- this.output.writeUTF("2");
- } catch (IOException ex) {
- ex.printStackTrace();
- exit(1);
- }
- this.logInWindow.setVisible(false);
- this.newUserWindow.setVisible(true);
- } else if (source == this.logInButton) {
- //Submit user name
- String result = "a";
- try {
- this.output.writeUTF(this.userField.getText());
- } catch (IOException ex) {
- ex.printStackTrace();
- exit(1);
- }
- result = this.inputThread.getInputData();
- if (!result.equals("Enter password:")) {
- JOptionPane.showMessageDialog(this.existingUserWindow, result);
- return;
- }
- //Submit password
- try {
- this.output.writeUTF(this.passField.getText());
- } catch (IOException ex) {
- ex.printStackTrace();
- exit(1);
- }
- result = this.inputThread.getInputData();
- if (!result.equals("Welcome to the chat! Type /help for a list of commands.")) {
- JOptionPane.showMessageDialog(this.existingUserWindow, result);
- return;
- }
- //Switch windows
- this.existingUserWindow.setVisible(false);
- //this.inputThread.updateShouldListen(true);
- this.setVisible(true);
- //Populate the users list
- try {
- this.output.writeUTF("/users");
- } catch (IOException ex) {
- ex.printStackTrace();
- exit(1);
- }
- } else if (source == this.registerButton) {
- //Submit user name
- String result = "a";
- try {
- this.output.writeUTF(this.regUserField.getText());
- } catch (IOException ex) {
- ex.printStackTrace();
- exit(1);
- }
- result = this.inputThread.getInputData();
- if (!result.equals("Enter password:")) {
- JOptionPane.showMessageDialog(this.newUserWindow, result);
- return;
- }
- //Submit password
- try {
- this.output.writeUTF(this.regPassField.getText());
- } catch (IOException ex) {
- ex.printStackTrace();
- exit(1);
- }
- result = this.inputThread.getInputData();
- if (!result.equals("Confirm password:")) {
- JOptionPane.showMessageDialog(this.newUserWindow, result);
- return;
- }
- //Submit password confirmation
- try {
- this.output.writeUTF(this.confirmField.getText());
- } catch (IOException ex) {
- ex.printStackTrace();
- exit(1);
- }
- result = this.inputThread.getInputData();
- if (!result.equals("Welcome to the chat! Type /help for a list of commands.")) {
- JOptionPane.showMessageDialog(this.newUserWindow, result);
- return;
- }
- this.newUserWindow.setVisible(false);
- //this.inputThread.updateShouldListen(true);
- this.setVisible(true);
- //Populate users list
- try {
- this.output.writeUTF("/users");
- } catch (IOException ex) {
- ex.printStackTrace();
- exit(1);
- }
- } else if (source == this.bHelp) {
- try {
- this.output.writeUTF("/help");
- } catch (IOException ex) {
- ex.printStackTrace();
- exit(1);
- }
- } else if (source == this.bLogout) {
- try {
- this.output.writeUTF("/logout");
- } catch (IOException ex) {
- ex.printStackTrace();
- exit(1);
- }
- exit(0);
- } else if (source == this.bSend) {
- String text = this.messageBox.getText();
- text = text.replace("\n", "");
- try {
- this.output.writeUTF(text);
- } catch (IOException ex) {
- ex.printStackTrace();
- exit(1);
- }
- this.messageBox.setText("");
- }
- }
- void setInputThread(ClientInputThread in) {
- this.inputThread = in;
- }
- void setOutputStream(DataOutputStream out) {
- this.output = out;
- }
- void addMessageToBox(String message) {
- System.out.println(this.chatBox.getText() + message + "\n");
- this.chatBox.setText(this.chatBox.getText() + message + "\n");
- this.chatPane.getVerticalScrollBar().setValue(this.chatPane.getVerticalScrollBar().getMaximum());
- }
- void addUserToList(String userName) {
- this.onlineUsers.add(userName);
- String currentList = "";
- Iterator<String> it = this.onlineUsers.iterator();
- while (it.hasNext()) {
- currentList = currentList.concat(it.next());
- currentList = currentList.concat("\n");
- }
- this.usersList.setText(currentList);
- this.usersPane.getVerticalScrollBar().setValue(this.usersPane.getVerticalScrollBar().getMaximum());
- }
- void clearUserList() {
- this.onlineUsers = new HashSet<>();
- }
- void updateUsersList() {
- try {
- this.output.writeUTF("/users");
- } catch (IOException ex) {
- ex.printStackTrace();
- exit(1);
- }
- }
- }
- //Thread class to handle input -- receiving data from server
- class ClientInputThread implements Runnable {
- //Instance variables
- private Socket socket;
- private Thread t;
- private ClientGUI gui;
- private String text;
- private DataInputStream input;
- private Queue<String> q;
- //Constructor.
- ClientInputThread(Socket s) {
- this.socket = s;
- }
- public void run() {
- //Set up connection variables
- this.input = null;
- try {
- input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
- } catch (IOException e) {
- System.err.println(e);
- exit(1);
- }
- //Set up the list of expected status messages
- Set<String> statusMessages = new HashSet<>();
- statusMessages.add("Usernames cannot contain ':'. Please try again.");
- statusMessages.add("Username already exists. Please try again.");
- statusMessages.add("Username does not exist. Try again.");
- statusMessages.add("Enter password:");
- statusMessages.add("Password must be greater than 0 characters.");
- statusMessages.add("Confirm password:");
- statusMessages.add("Passwords do not match. Try again.");
- statusMessages.add("Welcome to the chat! Type /help for a list of commands.");
- statusMessages.add("Authentication failed.");
- this.q = new LinkedList<>();
- //Program loop. Echo text to the console. Loop ends when main thread kills this thread
- this.text = "a";
- while (true) {
- try {
- System.out.println(this.text);
- this.text = input.readUTF();
- if (statusMessages.contains(this.text)) {
- q.add(this.text);
- } else {
- if (this.text.startsWith("Here are the connected users:")) {
- this.gui.clearUserList();
- this.text = input.readUTF();
- while (!this.text.equals(":end")) {
- this.gui.addUserToList(this.text);
- this.text = input.readUTF();
- }
- } else {
- if (this.text.startsWith("User")) {
- this.gui.updateUsersList();
- }
- this.gui.addMessageToBox(this.text);
- }
- }
- } catch (IOException e) {
- }
- }
- }
- public void start() {
- if(this.t == null) {
- t = new Thread(this);
- t.start();
- }
- }
- public void kill() {
- t.interrupt();
- }
- void setGUI(ClientGUI g) {
- this.gui = g;
- }
- String getInputData() {
- while(q.isEmpty()) {
- //Busy wait
- System.out.print("");
- }
- Iterator<String> it = this.q.iterator();
- while(it.hasNext()) {
- System.out.println(it.next());
- }
- return this.q.remove();
- }
- void closeInputStream() {
- try {
- input.close();
- this.socket.close();
- } catch (IOException e) {
- System.err.println(e);
- exit(1);
- }
- }
- }
- public class Client {
- public static void main(String[] args) {
- //Set up connection variables
- String hostName = "23.113.168.193";
- int portNumber = 9098;
- Socket socket = null;
- Scanner console = new Scanner(System.in);
- DataOutputStream output = null;
- //Set up GUI
- ClientGUI gui = new ClientGUI();
- //Establish connection to server
- try {
- socket = new Socket(hostName, portNumber);
- } catch (NullPointerException e) {
- System.err.println("Could not complete connection to server. Please try again.");
- exit(1);
- } catch (IOException e) {
- System.err.println(e);
- exit(1);
- }
- //Create a separate thread to handle receiving data from server.
- ClientInputThread in = new ClientInputThread(socket);
- in.start();
- //Get output stream
- try {
- output = new DataOutputStream(socket.getOutputStream());
- } catch (IOException e) {
- System.err.println(e);
- exit(1);
- }
- //Allow the GUI and the input thread to reference each other
- in.setGUI(gui);
- gui.setInputThread(in);
- gui.setOutputStream(output);
- //Program loop. Send commands to server.
- String line = "a", userName = null, password = null;
- while (!line.equals("/logout")) {
- try {
- line = console.nextLine();
- if (!line.equals("")) {
- output.writeUTF(line);
- }
- } catch (IOException e) {
- System.err.println(e);
- exit(1);
- }
- }
- //Close connection.
- try {
- console.close();
- output.close();
- socket.close();
- in.kill();
- } catch (IOException e) {
- System.err.println(e);
- exit(1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement