Advertisement
Guest User

Untitled

a guest
Mar 1st, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.19 KB | None | 0 0
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.awt.event.KeyAdapter;
  6. import java.awt.event.KeyEvent;
  7. import java.io.DataOutputStream;
  8. import java.io.BufferedInputStream;
  9. import java.io.DataInputStream;
  10. import java.io.IOException;
  11. import java.net.Socket;
  12. import java.util.*;
  13.  
  14. import static java.lang.System.exit;
  15.  
  16. class ClientGUI extends JFrame implements ActionListener{
  17. //GUI Objects
  18. private final JButton bLogout, bSend, bHelp, existButton, newButton, logInButton, registerButton;
  19. private final JTextField userField, passField, regUserField, regPassField, confirmField;
  20. private final JFrame logInWindow, existingUserWindow, newUserWindow;
  21. private final JTextArea messageBox, chatBox, usersList;
  22. private final JScrollPane chatPane, messagePane, usersPane;
  23.  
  24. private ClientInputThread inputThread;
  25. private DataOutputStream output;
  26.  
  27. private Set<String> onlineUsers;
  28.  
  29. //Constructor
  30. public ClientGUI() {
  31.  
  32. this.onlineUsers = new HashSet<>();
  33.  
  34. //Instantiate objects
  35. this.bLogout = new JButton("Log Out");
  36. this.bSend = new JButton("Send");
  37. this.bHelp = new JButton("Help");
  38.  
  39. this.messageBox = new JTextArea(5, 81);
  40. this.chatBox = new JTextArea(25, 81);
  41. this.usersList = new JTextArea(25, 18);
  42.  
  43. // this.chatBox.setPreferredSize(new Dimension(900, 400));
  44. //this.usersList.setPreferredSize(new Dimension(200, 400));
  45. //this.messageBox.setPreferredSize(new Dimension(900, 100));
  46. this.bSend.setPreferredSize(new Dimension(200, 100));
  47.  
  48. this.messageBox.setBorder(new JTextField().getBorder());
  49. this.messageBox.setLineWrap(true);
  50.  
  51. this.messageBox.addKeyListener(new KeyAdapter(){
  52. @Override
  53. public void keyReleased(KeyEvent ev) {
  54. if(ev.getKeyCode() == KeyEvent.VK_ENTER) {
  55. actionPerformed(new ActionEvent(bSend, 0, ""));
  56. }
  57. }
  58. });
  59.  
  60. this.chatBox.setBorder(new JTextField().getBorder());
  61. this.chatBox.setLineWrap(true);
  62. this.chatBox.setEditable(false);
  63.  
  64. this.usersList.setBorder(new JTextField().getBorder());
  65. this.usersList.setLineWrap(false);
  66. this.usersList.setEditable(false);
  67.  
  68. //Set up scroll panes
  69. this.chatPane = new JScrollPane(this.chatBox);
  70. this.usersPane = new JScrollPane(this.usersList);
  71. this.messagePane = new JScrollPane(this.messageBox);
  72.  
  73. //Set up main window
  74. this.setLayout(new GridBagLayout());
  75. GridBagConstraints c = new GridBagConstraints();
  76.  
  77. JPanel buttonPanel = new JPanel(new GridBagLayout());
  78. c.gridx = 0;
  79. c.gridy = 0;
  80. c.fill = GridBagConstraints.HORIZONTAL;
  81. c.anchor = GridBagConstraints.FIRST_LINE_START;
  82. buttonPanel.add(this.bHelp, c);
  83. c.gridx = 1;
  84. c.gridy = 0;
  85. c.anchor = GridBagConstraints.FIRST_LINE_START;
  86. buttonPanel.add(this.bLogout, c);
  87. c.gridx = 2;
  88. c.gridy = 0;
  89. c.insets = new Insets(10, 770, 0, 135);
  90. c.fill = GridBagConstraints.NONE;
  91. c.anchor = GridBagConstraints.FIRST_LINE_END;
  92. buttonPanel.add(new JLabel("Online Users"), c);
  93. c.insets = new Insets(0, 0 , 0 , 0);
  94. c.gridx = 0;
  95. c.gridy = 0;
  96. this.add(buttonPanel, c);
  97.  
  98. JPanel messagePanel = new JPanel(new FlowLayout());
  99. messagePanel.add(chatPane);
  100. messagePanel.add(usersPane);
  101. c.gridx = 0;
  102. c.gridy = 1;
  103. this.add(messagePanel, c);
  104.  
  105. JPanel bottomPanel = new JPanel(new GridBagLayout());
  106. c = new GridBagConstraints();
  107. c.gridx = 0;
  108. c.gridy = 0;
  109. bottomPanel.add(messagePane, c);
  110. c.gridx = 1;
  111. c.gridy = 0;
  112. c.insets = new Insets(0, 7, 0, 3);
  113. bottomPanel.add(this.bSend, c);
  114. c.gridx = 0;
  115. c.gridy = 2;
  116. this.add(bottomPanel, c);
  117.  
  118. //Make window invisible until user logs in
  119. this.getRootPane().setDefaultButton(this.bSend);
  120. this.setTitle("CSE3461 Chat");
  121. this.setResizable(false);
  122. this.setLocationRelativeTo(null);
  123. this.pack();
  124. this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  125. this.setVisible(false);
  126.  
  127. //Create log in or register window
  128. this.logInWindow = new JFrame();
  129. this.logInWindow.setTitle("Log In or Register");
  130. this.logInWindow.setResizable(false);
  131. this.logInWindow.setPreferredSize(new Dimension(290, 125));
  132.  
  133. JPanel logInPanel = new JPanel(new GridLayout(2, 2));
  134. JLabel existing = new JLabel("Existing Users");
  135. JLabel newU = new JLabel("New Users");
  136. existing.setHorizontalAlignment(JLabel.CENTER);
  137. newU.setHorizontalAlignment(JLabel.CENTER);
  138. logInPanel.add(existing);
  139. logInPanel.add(newU);
  140. this.existButton = new JButton("Log In");
  141. this.newButton = new JButton("Register");
  142. this.existButton.addActionListener(this);
  143. this.newButton.addActionListener(this);
  144. logInPanel.add(this.existButton);
  145. logInPanel.add(this.newButton);
  146.  
  147. this.logInWindow.add(logInPanel);
  148.  
  149. //Set up action listeners
  150. this.bHelp.addActionListener(this);
  151. this.bLogout.addActionListener(this);
  152. this.bSend.addActionListener(this);
  153.  
  154. this.logInWindow.pack();
  155. this.logInWindow.setLocationRelativeTo(null);
  156. this.logInWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  157. this.logInWindow.setVisible(true);
  158.  
  159. //Create username entry window
  160. this.existingUserWindow = new JFrame();
  161. this.existingUserWindow.setTitle("Log In");
  162. this.existingUserWindow.setResizable(false);
  163. this.existingUserWindow.setPreferredSize(new Dimension(250, 200));
  164.  
  165. JPanel existingUserPanel = new JPanel(new GridLayout(5, 1));
  166. JLabel userLabel = new JLabel("User Name:");
  167. JLabel passLabel = new JLabel("Password:");
  168. this.userField = new JTextField();
  169. this.passField = new JPasswordField();
  170. this.logInButton = new JButton("Log In");
  171. existingUserPanel.add(userLabel);
  172. existingUserPanel.add(this.userField);
  173. existingUserPanel.add(passLabel);
  174. existingUserPanel.add(this.passField);
  175. existingUserPanel.add(this.logInButton);
  176.  
  177. this.logInButton.addActionListener(this);
  178.  
  179. this.existingUserWindow.add(existingUserPanel);
  180.  
  181. this.existingUserWindow.getRootPane().setDefaultButton(this.logInButton);
  182. this.existingUserWindow.pack();
  183. this.existingUserWindow.setLocationRelativeTo(null);
  184. this.existingUserWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  185.  
  186. //Create register user window
  187. this.newUserWindow = new JFrame();
  188. this.newUserWindow.setTitle("Register User");
  189. this.newUserWindow.setResizable(false);
  190. this.newUserWindow.setPreferredSize(new Dimension(275, 250));
  191.  
  192. JPanel newUserPanel = new JPanel(new GridLayout(7, 1));
  193. userLabel = new JLabel("User Name:");
  194. passLabel = new JLabel("Password:");
  195. this.regUserField = new JTextField();
  196. this.regPassField = new JPasswordField();
  197. this.registerButton = new JButton("Register");
  198. JLabel confirmLabel = new JLabel("Confirm Password:");
  199. this.confirmField = new JPasswordField();
  200. newUserPanel.add(userLabel);
  201. newUserPanel.add(this.regUserField);
  202. newUserPanel.add(passLabel);
  203. newUserPanel.add(this.regPassField);
  204. newUserPanel.add(confirmLabel);
  205. newUserPanel.add(this.confirmField);
  206. newUserPanel.add(this.registerButton);
  207.  
  208. this.registerButton.addActionListener(this);
  209.  
  210. this.newUserWindow.add(newUserPanel);
  211.  
  212. this.newUserWindow.getRootPane().setDefaultButton(this.registerButton);
  213. this.newUserWindow.pack();
  214. this.newUserWindow.setLocationRelativeTo(null);
  215. this.newUserWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  216. }
  217.  
  218. @Override
  219. public void actionPerformed(ActionEvent e) {
  220. Object source = e.getSource();
  221. if (source == this.existButton) {
  222. try {
  223. this.output.writeUTF("1");
  224. } catch (IOException ex) {
  225. ex.printStackTrace();
  226. exit(1);
  227. }
  228. this.logInWindow.setVisible(false);
  229. this.existingUserWindow.setVisible(true);
  230. } else if (source == this.newButton) {
  231. try {
  232. this.output.writeUTF("2");
  233. } catch (IOException ex) {
  234. ex.printStackTrace();
  235. exit(1);
  236. }
  237. this.logInWindow.setVisible(false);
  238. this.newUserWindow.setVisible(true);
  239. } else if (source == this.logInButton) {
  240. //Submit user name
  241. String result = "a";
  242. try {
  243. this.output.writeUTF(this.userField.getText());
  244. } catch (IOException ex) {
  245. ex.printStackTrace();
  246. exit(1);
  247. }
  248. result = this.inputThread.getInputData();
  249. if (!result.equals("Enter password:")) {
  250. JOptionPane.showMessageDialog(this.existingUserWindow, result);
  251. return;
  252. }
  253.  
  254. //Submit password
  255. try {
  256. this.output.writeUTF(this.passField.getText());
  257. } catch (IOException ex) {
  258. ex.printStackTrace();
  259. exit(1);
  260. }
  261. result = this.inputThread.getInputData();
  262. if (!result.equals("Welcome to the chat! Type /help for a list of commands.")) {
  263. JOptionPane.showMessageDialog(this.existingUserWindow, result);
  264. return;
  265. }
  266.  
  267. //Switch windows
  268. this.existingUserWindow.setVisible(false);
  269. //this.inputThread.updateShouldListen(true);
  270. this.setVisible(true);
  271.  
  272. //Populate the users list
  273. try {
  274. this.output.writeUTF("/users");
  275. } catch (IOException ex) {
  276. ex.printStackTrace();
  277. exit(1);
  278. }
  279. } else if (source == this.registerButton) {
  280. //Submit user name
  281. String result = "a";
  282. try {
  283. this.output.writeUTF(this.regUserField.getText());
  284. } catch (IOException ex) {
  285. ex.printStackTrace();
  286. exit(1);
  287. }
  288. result = this.inputThread.getInputData();
  289. if (!result.equals("Enter password:")) {
  290. JOptionPane.showMessageDialog(this.newUserWindow, result);
  291. return;
  292. }
  293.  
  294. //Submit password
  295. try {
  296. this.output.writeUTF(this.regPassField.getText());
  297. } catch (IOException ex) {
  298. ex.printStackTrace();
  299. exit(1);
  300. }
  301. result = this.inputThread.getInputData();
  302. if (!result.equals("Confirm password:")) {
  303. JOptionPane.showMessageDialog(this.newUserWindow, result);
  304. return;
  305. }
  306.  
  307. //Submit password confirmation
  308. try {
  309. this.output.writeUTF(this.confirmField.getText());
  310. } catch (IOException ex) {
  311. ex.printStackTrace();
  312. exit(1);
  313. }
  314. result = this.inputThread.getInputData();
  315. if (!result.equals("Welcome to the chat! Type /help for a list of commands.")) {
  316. JOptionPane.showMessageDialog(this.newUserWindow, result);
  317. return;
  318. }
  319.  
  320. this.newUserWindow.setVisible(false);
  321. //this.inputThread.updateShouldListen(true);
  322. this.setVisible(true);
  323.  
  324. //Populate users list
  325. try {
  326. this.output.writeUTF("/users");
  327. } catch (IOException ex) {
  328. ex.printStackTrace();
  329. exit(1);
  330. }
  331.  
  332. } else if (source == this.bHelp) {
  333. try {
  334. this.output.writeUTF("/help");
  335. } catch (IOException ex) {
  336. ex.printStackTrace();
  337. exit(1);
  338. }
  339. } else if (source == this.bLogout) {
  340. try {
  341. this.output.writeUTF("/logout");
  342. } catch (IOException ex) {
  343. ex.printStackTrace();
  344. exit(1);
  345. }
  346. exit(0);
  347. } else if (source == this.bSend) {
  348. String text = this.messageBox.getText();
  349. text = text.replace("\n", "");
  350. try {
  351. this.output.writeUTF(text);
  352. } catch (IOException ex) {
  353. ex.printStackTrace();
  354. exit(1);
  355. }
  356. this.messageBox.setText("");
  357. }
  358. }
  359.  
  360. void setWindowVisible(boolean value) {
  361. this.setVisible(value);
  362. }
  363.  
  364. void setInputThread(ClientInputThread in) {
  365. this.inputThread = in;
  366. }
  367.  
  368. void setOutputStream(DataOutputStream out) {
  369. this.output = out;
  370. }
  371.  
  372. void addMessageToBox(String message) {
  373. System.out.println(this.chatBox.getText() + message + "\n");
  374. this.chatBox.setText(this.chatBox.getText() + message + "\n");
  375. this.chatPane.getVerticalScrollBar().setValue(this.chatPane.getVerticalScrollBar().getMaximum());
  376. }
  377.  
  378. void addUserToList(String userName) {
  379. this.onlineUsers.add(userName);
  380. String currentList = "";
  381. Iterator<String> it = this.onlineUsers.iterator();
  382. while (it.hasNext()) {
  383. currentList = currentList.concat(it.next());
  384. currentList = currentList.concat("\n");
  385. }
  386. this.usersList.setText(currentList);
  387. this.usersPane.getVerticalScrollBar().setValue(this.usersPane.getVerticalScrollBar().getMaximum());
  388. }
  389.  
  390. void removeUserFromList(String userName) {
  391. this.onlineUsers.remove(userName);
  392. String currentList = "";
  393. Iterator<String> it = this.onlineUsers.iterator();
  394. while (it.hasNext()) {
  395. currentList = currentList.concat(it.next());
  396. currentList = currentList.concat("\n");
  397. }
  398. this.usersList.setText(currentList);
  399. this.usersPane.getVerticalScrollBar().setValue(this.usersPane.getVerticalScrollBar().getMaximum());
  400. }
  401.  
  402. void clearUserList() {
  403. this.onlineUsers = new HashSet<>();
  404. }
  405.  
  406. void updateUsersList() {
  407. try {
  408. this.output.writeUTF("/users");
  409. } catch (IOException ex) {
  410. ex.printStackTrace();
  411. exit(1);
  412. }
  413. }
  414. }
  415.  
  416. //Thread class to handle input -- receiving data from server
  417. class ClientInputThread implements Runnable {
  418. //Instance variables
  419. private Socket socket;
  420. private Thread t;
  421. private ClientGUI gui;
  422. private String text;
  423. private DataInputStream input;
  424. private Queue<String> q;
  425.  
  426. //Constructor.
  427. ClientInputThread(Socket s) {
  428. this.socket = s;
  429. }
  430.  
  431. public void run() {
  432. //Set up connection variables
  433. this.input = null;
  434. try {
  435. input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
  436. } catch (IOException e) {
  437. System.err.println(e);
  438. exit(1);
  439. }
  440.  
  441. //Set up the list of expected status messages
  442. Set<String> statusMessages = new HashSet<>();
  443. statusMessages.add("Usernames cannot contain ':'. Please try again.");
  444. statusMessages.add("Username already exists. Please try again.");
  445. statusMessages.add("Username does not exist. Try again.");
  446. statusMessages.add("Enter password:");
  447. statusMessages.add("Password must be greater than 0 characters.");
  448. statusMessages.add("Confirm password:");
  449. statusMessages.add("Passwords do not match. Try again.");
  450. statusMessages.add("Welcome to the chat! Type /help for a list of commands.");
  451. statusMessages.add("Authentication failed.");
  452.  
  453. this.q = new LinkedList<>();
  454.  
  455. //Program loop. Echo text to the console. Loop ends when main thread kills this thread
  456. this.text = "a";
  457. while (true) {
  458. try {
  459. System.out.println(this.text);
  460. this.text = input.readUTF();
  461. if (statusMessages.contains(this.text)) {
  462. q.add(this.text);
  463. } else {
  464. if (this.text.startsWith("Here are the connected users:")) {
  465. this.gui.clearUserList();
  466. this.text = input.readUTF();
  467. while (!this.text.equals(":end")) {
  468. this.gui.addUserToList(this.text);
  469. this.text = input.readUTF();
  470. }
  471. } else {
  472. if (this.text.startsWith("User")) {
  473. this.gui.updateUsersList();
  474. }
  475. this.gui.addMessageToBox(this.text);
  476. }
  477. }
  478. } catch (IOException e) {
  479. }
  480. }
  481. }
  482.  
  483. public void start() {
  484. if(this.t == null) {
  485. t = new Thread(this);
  486. t.start();
  487. }
  488. }
  489.  
  490. public void kill() {
  491. t.interrupt();
  492. }
  493.  
  494. void setGUI(ClientGUI g) {
  495. this.gui = g;
  496. }
  497.  
  498. String getInputData() {
  499. while(q.isEmpty()) {
  500. //Busy wait
  501. System.out.print("");
  502. }
  503. Iterator<String> it = this.q.iterator();
  504. while(it.hasNext()) {
  505. System.out.println(it.next());
  506. }
  507. return this.q.remove();
  508. }
  509.  
  510. void closeInputStream() {
  511. try {
  512. input.close();
  513. this.socket.close();
  514. } catch (IOException e) {
  515. System.err.println(e);
  516. exit(1);
  517. }
  518. }
  519. }
  520.  
  521. public class Client {
  522.  
  523. public static void main(String[] args) {
  524. //Set up connection variables
  525. String hostName = "23.113.168.193";
  526. int portNumber = 9098;
  527. Socket socket = null;
  528. Scanner console = new Scanner(System.in);
  529. DataOutputStream output = null;
  530.  
  531. //Set up GUI
  532. ClientGUI gui = new ClientGUI();
  533.  
  534. //Establish connection to server
  535. try {
  536. socket = new Socket(hostName, portNumber);
  537. } catch (NullPointerException e) {
  538. System.err.println("Could not complete connection to server. Please try again.");
  539. exit(1);
  540. } catch (IOException e) {
  541. System.err.println(e);
  542. exit(1);
  543. }
  544.  
  545. //Create a separate thread to handle receiving data from server.
  546. ClientInputThread in = new ClientInputThread(socket);
  547. in.start();
  548.  
  549. //Get output stream
  550. try {
  551. output = new DataOutputStream(socket.getOutputStream());
  552. } catch (IOException e) {
  553. System.err.println(e);
  554. exit(1);
  555. }
  556.  
  557. //Allow the GUI and the input thread to reference each other
  558. in.setGUI(gui);
  559. gui.setInputThread(in);
  560. gui.setOutputStream(output);
  561.  
  562. //Program loop. Send commands to server.
  563. String line = "a", userName = null, password = null;
  564. while (!line.equals("/logout")) {
  565. try {
  566. line = console.nextLine();
  567. if (!line.equals("")) {
  568. output.writeUTF(line);
  569. }
  570. } catch (IOException e) {
  571. System.err.println(e);
  572. exit(1);
  573. }
  574. }
  575.  
  576. //Close connection.
  577. try {
  578. console.close();
  579. output.close();
  580. socket.close();
  581. in.kill();
  582. } catch (IOException e) {
  583. System.err.println(e);
  584. exit(1);
  585. }
  586. }
  587. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement