Advertisement
Guest User

Untitled

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