Advertisement
Guest User

Untitled

a guest
Mar 8th, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 23.86 KB | None | 0 0
  1. //Student Name: Adam McGivern
  2.  
  3. //Student Number: 40086043
  4. //Module Code: CSC 2008
  5. //Practical Day: Monday
  6. //Email: amcgivern11@qub.ac.uk
  7.  
  8. import java.awt.*;
  9. import java.awt.event.*;
  10.  
  11. import javax.swing.*;
  12.  
  13. import java.io.*;
  14. import java.net.*;
  15. import java.text.SimpleDateFormat;
  16. import java.util.Calendar;
  17.  
  18. import javax.swing.text.*;
  19.  
  20.  
  21. public class Chat_Client extends JFrame
  22. { // socket to communicate with server
  23. Socket socket;
  24. // input stream - data sent by the server will be read from this stream
  25. ObjectInputStream clientInputStream;
  26. // output stream - data sent to the server will be written to this stream
  27. ObjectOutputStream clientOutputStream;
  28.  
  29. // variables for the GUI components of the game
  30. Container c;
  31. ButtonHandler bHandler, spHandler, schander, dcHandler, colour;
  32. NameButtonHandler nbHandler;
  33. ImageButtonHandler ibHandler;
  34. JButton sendButton, logonButton, saveConvo, Leave;
  35. JButton[] nameButtons, imageButtons;
  36. ImageIcon[] images = {new ImageIcon("smile.gif"), new ImageIcon("frown.gif"), new ImageIcon("wink.gif"), new ImageIcon("eek.gif"), new ImageIcon("confused.gif"), new ImageIcon("embarrassed.gif"), new ImageIcon("stop.gif")};
  37. JPasswordField password;
  38. JTextField username;
  39. JTextPane outputArea,inputArea;
  40. StyledDocument docInputArea, docOutputArea;
  41. Style style;
  42. JPanel namesPanel, imageButtonsPanel, nameButtonsPanel, sendButtonPanel,inputAreaPanel, logonFieldsPanel, logonButtonPanel, leftPanel, rightPanel, cCenterPanel, lowerPanel, outputAreaPanel;
  43. JLabel namesLabel, usernameLabel, passwordLabel, imageLabel;
  44.  
  45. String [] names = {"Arken", "Ben", "Darklark", "Free", "Group"};
  46. //boolean[] loggedOn = new boolean[5];
  47. boolean[] loggedIn = {false, false, false, false, true};
  48. String recipients = "";
  49. String plainTextPW = "";
  50. String message;
  51.  
  52. public Chat_Client()
  53. { super("Chat_Client");
  54. addWindowListener
  55. ( new WindowAdapter()
  56. { public void windowClosing(WindowEvent e)
  57. {
  58. sendMessage("quit");
  59.  
  60.  
  61. }
  62. }
  63. );
  64.  
  65. /* the initial GUI will provide a text field and password field
  66. to enable the user to enter their username and password and
  67. attempt to logon to the game system */
  68.  
  69. // create and add GUI components
  70. c = getContentPane();
  71. c.setLayout(new BorderLayout());
  72.  
  73. // GUI components for the username
  74. logonFieldsPanel = new JPanel();
  75. logonFieldsPanel.setLayout(new GridLayout(2,2,5,5));
  76. usernameLabel = new JLabel("Enter Username: ");
  77. logonFieldsPanel.add(usernameLabel);
  78. username = new JTextField(10);
  79. logonFieldsPanel.add(username);
  80.  
  81. // GUI components for the password
  82. passwordLabel = new JLabel("Enter Your Password: ");
  83. logonFieldsPanel.add(passwordLabel);
  84. password = new JPasswordField(10);
  85. logonFieldsPanel.add(password);
  86. c.add(logonFieldsPanel,BorderLayout.CENTER);
  87.  
  88. // panel for the logon button
  89. logonButtonPanel = new JPanel();
  90. logonButton = new JButton("logon");
  91.  
  92. bHandler = new ButtonHandler();
  93. logonButton.addActionListener(bHandler);
  94. logonButtonPanel.add(logonButton);
  95.  
  96. c.add(logonButtonPanel, BorderLayout.SOUTH);
  97.  
  98. setSize(300,125);
  99. setResizable(false);
  100. setVisible(true);
  101. setLocation(400,250);
  102. }
  103.  
  104.  
  105. void setUpChatClient(boolean chatting)
  106. { // remove iniial GUI components (textfield, password field, logon button)
  107. c.remove(logonButtonPanel);
  108. c.remove(logonFieldsPanel);
  109.  
  110. if(!chatting)
  111. // if the user has not logged on an error message will be displayed
  112. c.add(new JTextArea("Logon unsuccessful"));
  113. else
  114. { // if the user has logged on the message service GUI will be set up
  115. c.setLayout(new BorderLayout());
  116. leftPanel = new JPanel(new GridLayout(2,1));
  117. leftPanel.setBackground(Color.WHITE);
  118. rightPanel = new JPanel(new GridLayout(2,1));
  119.  
  120.  
  121. // name buttons enable user to choose message recipient(s)
  122. nameButtonsPanel = new JPanel(new GridLayout(5,1));
  123. nameButtons = new JButton[names.length];
  124. nbHandler = new NameButtonHandler();
  125. for(int r = 0; r < nameButtons.length; r++)
  126. { nameButtons[r] = new JButton(names[r]);
  127. nameButtons[r].addActionListener(nbHandler);
  128. nameButtons[r].setEnabled(loggedIn[r]);
  129. nameButtonsPanel.add(nameButtons[r]);
  130. }
  131. leftPanel.add(nameButtonsPanel);
  132.  
  133. outputAreaPanel = new JPanel();
  134. outputAreaPanel.setBackground(Color.WHITE);
  135. // messages from the server will be displayed in this JTextPane
  136. outputArea = new JTextPane();
  137. outputArea.setEditable(false);
  138. Dimension d = new Dimension(300,150);
  139. outputArea.setPreferredSize(d);
  140. docOutputArea = (StyledDocument) outputArea.getDocument();
  141. style = docOutputArea.addStyle("StyleName", null);
  142. JScrollPane outputScrollPane = new JScrollPane(outputArea);
  143. outputAreaPanel.add(outputScrollPane);
  144. rightPanel.add(outputAreaPanel);
  145.  
  146. inputAreaPanel = new JPanel();
  147. inputAreaPanel.setBackground(Color.WHITE);
  148. // image buttons enable user to add an image to a text message
  149. imageButtonsPanel = new JPanel();
  150. imageButtonsPanel.setBackground(Color.WHITE);
  151. d = new Dimension(25,25);
  152. ibHandler = new ImageButtonHandler();
  153. imageButtons = new JButton[images.length];
  154. for(int j = 0; j < imageButtons.length; j++)
  155. { imageButtons[j] = new JButton(images[j]);
  156. imageButtons[j].setPreferredSize(d);
  157. imageButtons[j].setBorderPainted(false);
  158. imageButtons[j].addActionListener(ibHandler);
  159. imageButtonsPanel.add(imageButtons[j]);
  160. }
  161. inputAreaPanel.add(imageButtonsPanel);
  162.  
  163. d = new Dimension(300,60);
  164. // text messages will be entered into this JTextPane
  165. inputArea = new JTextPane();
  166. inputArea.setPreferredSize(d);
  167. docInputArea = (StyledDocument) inputArea.getDocument();
  168. style = docInputArea.addStyle("StyleName", null);
  169. JScrollPane scrollPane = new JScrollPane(inputArea);
  170. inputAreaPanel.add(scrollPane);
  171.  
  172. // the send button enables user to send a text message
  173. sendButtonPanel = new JPanel(new GridLayout(2,2));
  174. sendButtonPanel.setBackground(Color.WHITE);
  175. bHandler = new ButtonHandler();
  176. sendButton = new JButton("Send");
  177. sendButton.addActionListener(bHandler);
  178. sendButtonPanel.add(sendButton);
  179. inputAreaPanel.add(sendButtonPanel);
  180. rightPanel.add(inputAreaPanel);
  181.  
  182.  
  183. saveConvo = new JButton("Save Chat Log");
  184. schander = new ButtonHandler();
  185. saveConvo.addActionListener(schander);
  186. sendButtonPanel.add(saveConvo);
  187.  
  188. Leave = new JButton("Leave");
  189. dcHandler = new ButtonHandler();
  190. Leave.addActionListener(dcHandler);
  191. sendButtonPanel.add(Leave);
  192.  
  193.  
  194. c.add(rightPanel, BorderLayout.CENTER);
  195. c.add(leftPanel, BorderLayout.WEST);
  196. setSize(425, 475);
  197. }
  198. setResizable(false);
  199. setVisible(true);
  200.  
  201. }
  202.  
  203. void changeNameButton(int i, Color c)
  204. { /* change the colour of the text on a name
  205. button - red indicates that this friend
  206. is a recipient of next message */
  207. nameButtons[i].setForeground(c);
  208. }
  209.  
  210. void changeNameButtons(Color c)
  211. { /* change the colour of the text on all the
  212. name buttons */
  213. for(int r = 0; r < nameButtons.length; r++)
  214. changeNameButton(r, c);
  215. }
  216.  
  217. void changeNameButtons()
  218. { /* disable or enable each name button - a
  219. button is enabled if that friend is online,
  220. otherwise it is disabled */
  221. for(int i = 0; i < loggedIn.length; i++)
  222. {
  223.  
  224. if(loggedIn[i] == true)
  225. {
  226. // If the user is in the names array, check the boolean value in the Array corresponding to that user.
  227. nameButtons[i].setEnabled(true);
  228.  
  229. }
  230. else
  231. loggedIn[i] = false;
  232.  
  233. }
  234. }
  235.  
  236. void changeFriends(String n, boolean t)
  237. { // change a friend's "online" status
  238. for(int i = 0; i < names.length; i++)
  239. {
  240. //If the value at loggedIn[i] is equal to true set the boolean to true, else set it to false
  241. if(n.equals(names[i]))
  242. {
  243. loggedIn[i] = t;
  244. //setEnabled(true);
  245.  
  246. }
  247. }
  248.  
  249. // call method to update buttons
  250. changeNameButtons();
  251. }
  252.  
  253. void addOutput(String str)
  254. { /* this will split the message string into words using the space
  255. character as a delimiter, the words will be stored in consecutive
  256. elements of array "words" */
  257. String[] words = str.split(" \\s*");
  258. try
  259. { // travese array, taking each word in turn
  260. for(int i = 0; i < words.length; i++)
  261. { /* if the first character of this word is $ this indicates that
  262. this string represents an image in the text message */
  263. if(words[i].charAt(0) == '$')
  264. { /* the remainder of this word will be a number indicating the
  265. array element in which the image is stored - retrieve this
  266. number from the string */
  267. String position = words[i].substring(1, words[i].length());
  268. // cast this string number to an int value
  269. int pos = Integer.parseInt(position);
  270. // retrieve the appropriate image from the array
  271. StyleConstants.setIcon(style, images[pos]);
  272. // add the image to the text output area
  273. docOutputArea.insertString(docOutputArea.getLength(), " $" + pos + " ", style);
  274. }
  275. else
  276. // otherwise add the next text word to the text output area
  277. docOutputArea.insertString(docOutputArea.getLength(), words[i] + " ", null);
  278. }
  279. // add a newline character to the text output area
  280. docOutputArea.insertString(docOutputArea.getLength(), " \n", null);
  281. // set the caret position in the text output area
  282. outputArea.setCaretPosition(docOutputArea.getLength());
  283. }
  284. catch(BadLocationException ee)
  285. { System.out.println(ee);
  286. System.exit(1);
  287. }
  288. }
  289.  
  290. void closeChatClient()
  291. { // user has quit the message service - disable GUI components
  292. // disable send message button
  293. sendButton.setEnabled(false);
  294. // disable all name buttons
  295. for(int i = 0; i < names.length; i++)
  296. {
  297. nameButtons[i].setEnabled(false);
  298. }
  299. // disable all image buttons
  300. for(int i = 0; i < imageButtons.length; i++ )
  301. {
  302. imageButtons[i].setEnabled(false);
  303. }
  304. // set input area to prevent text entry
  305. inputArea.setEditable(false);
  306.  
  307.  
  308.  
  309. }
  310.  
  311. void sendLoginDetails()
  312. { try
  313. { // get username from text field and encrypt
  314. EncryptedMessage uname = new EncryptedMessage(username.getText());
  315. uname.encrypt();
  316. // get password from password field and encrypt
  317.  
  318. EncryptedMessage pword = new EncryptedMessage(new String(password.getPassword()));
  319. pword.encrypt();
  320.  
  321. // send encrypted username to server
  322. clientOutputStream.writeObject(uname);
  323. // send encrypted password to server
  324. clientOutputStream.writeObject(pword);
  325.  
  326. }
  327. catch(IOException e) // thrown by methods writeObject
  328. { System.out.println(e);
  329. System.exit(1);
  330. }
  331. }
  332.  
  333. void getConnections()
  334. { try
  335. { // initialise a socket and get a connection to server
  336. socket = new Socket(InetAddress.getLocalHost(), 7500);
  337. // get input & output object streams
  338.  
  339. // get output stream
  340. clientOutputStream = new ObjectOutputStream(socket.getOutputStream());
  341.  
  342. // get input stream
  343. clientInputStream = new ObjectInputStream(socket.getInputStream());
  344.  
  345.  
  346. /* create a new thread of Chat_ClientThread, sending input
  347. stream variable as a parameter */
  348. Chat_ClientThread cct = new Chat_ClientThread(clientInputStream);
  349. // start thread - execution will begin at method run
  350. cct.start();
  351. }
  352. catch(UnknownHostException e) // thrown by method getLocalHost
  353. { System.out.println(e);
  354. System.exit(1);
  355. }
  356. catch(IOException e) // thrown by methods ObjectOutputStream, ObjectInputStream
  357. { System.out.println(e);
  358. System.exit(1);
  359. }
  360. }
  361.  
  362. void saveLog(){
  363. BufferedWriter BufferString = null;
  364. try {
  365. //create a temporary file
  366. String timeLog = new SimpleDateFormat("ddMMyyyy_HHmmss").format(Calendar.getInstance().getTime());
  367. File logPage = new File(timeLog + ".txt");
  368.  
  369. // This will output the full path where the file will be written to...
  370. System.out.println(logPage.getCanonicalPath());
  371.  
  372. BufferString = new BufferedWriter(new FileWriter(logPage));
  373. BufferString.write(outputArea.getText());
  374. } catch (Exception e) {
  375. e.printStackTrace();//exception
  376. } finally {
  377. try {
  378.  
  379. BufferString.close();// always close
  380.  
  381.  
  382. } catch (Exception e) {
  383. }
  384. }
  385. }
  386.  
  387. void sendMessage(String str)
  388. { try
  389. {
  390.  
  391. /* if you have not chosen any recipients this message will be
  392. sent to all friends by default */
  393. if(recipients.equals(""))
  394. recipients = names[names.length - 1] + ",";
  395. // separate recipients and the message by inserting # character
  396. str = recipients + "#" + str;
  397. // compress message
  398. CompressedMessage cm = new CompressedMessage(str);
  399. cm.compress();
  400. // send message to server
  401. clientOutputStream.writeObject(cm);
  402. // clear recipients for next message
  403. recipients = "";
  404. // clear the input area
  405. inputArea.setText("");
  406. // change the colour of text on name buttons of friends online
  407. changeNameButtons(Color.BLACK);
  408. }
  409. catch(IOException e) // thrown by method writeObject
  410. { System.out.println(e);
  411. System.exit(1);
  412. }
  413. }
  414.  
  415. void closeStreams()
  416. {
  417.  
  418. //Is this try needed?!
  419. try{
  420. // close input stream
  421. clientOutputStream.close();
  422. // close output stream
  423. clientInputStream.close();
  424. // close socket
  425. socket.close();
  426. }
  427. catch(IOException e) // thrown by method close
  428. { System.out.println(e);
  429. System.exit(1);
  430. }
  431. }
  432.  
  433. public static void main(String args[])
  434. { Chat_Client gameClient = new Chat_Client();
  435. gameClient.getConnections();
  436. }
  437.  
  438.  
  439. private class Chat_ClientThread extends Thread
  440. { ObjectInputStream threadInputStream;
  441.  
  442. public Chat_ClientThread(ObjectInputStream in)
  443. { // initialise input stream
  444. threadInputStream = in;
  445. }
  446.  
  447. // when method start() is called thread execution will begin in this method
  448. public void run()
  449. { try
  450. { /* read Boolean value sent by server - it is converted to
  451. a primitive boolean value */
  452. boolean chatting = (Boolean)threadInputStream.readObject();
  453. // call method to change the client GUI
  454. setUpChatClient(chatting);
  455. if(!chatting)
  456. // call method to close input & output streams & socket
  457. closeStreams();
  458. else
  459. { // this loop will continue until this client quits the chat service
  460. while(chatting)
  461. { // read next compressed message from server
  462. CompressedMessage nextMessage = (CompressedMessage)clientInputStream.readObject();
  463. // decompressed message
  464. nextMessage.decompress();
  465. // retrieve decompressed message
  466. //clientInputStream.readObject();
  467. String message = nextMessage.getMessage();
  468. // if this client has quit the server will send this last message
  469. if(message.equals("goodbye"))
  470. { // chatClient should be closed
  471.  
  472. closeChatClient();
  473. closeStreams();
  474. chatting = false;
  475.  
  476. }
  477.  
  478. else
  479. { if(message.substring(0,4).equals("join"))
  480. { /* if the first word in the message is "join" then another friend
  481. has joined the message service, retrieve the name of friend
  482. and enable their name button in GUI */
  483. changeFriends(message.substring(4,message.length()), true);
  484. for(int i = 0; i<loggedIn.length;i++)
  485. {
  486. if(message.substring(4,message.length()-1).equalsIgnoreCase(names[i]))
  487. {
  488. loggedIn[i] = true;
  489. nameButtons[i].setEnabled (true);
  490. }
  491.  
  492. }
  493. // output message in output area
  494. addOutput(message.substring(4,message.length()) + " has joined");
  495.  
  496. }
  497. else
  498. { if(message.substring(0,4).equals("quit"))
  499.  
  500. { /* if the first word in the message is "quit" then a friend
  501. has quit the message service, retrieve the name of friend
  502. and disable their name button in GUI */
  503. changeFriends(message.substring(4,message.length()-1), false);
  504. for(int i = 0; i<loggedIn.length;i++)
  505. {
  506. if(message.substring(4,message.length()-1).equalsIgnoreCase(names[i]))
  507. {
  508. loggedIn[i] = false;
  509. nameButtons[i].setEnabled (false);
  510. }
  511. }
  512.  
  513. // output message in output area
  514. addOutput(message.substring(4,message.length()) + " has quit");
  515.  
  516.  
  517. }
  518. else
  519. { if(message.substring(0,6).equals("online"))
  520. { /* if the first word in the message is "online" then this client
  521. has just joined the chat service and this message lists
  522. the names of all other friends that are online */
  523. // split string to separate names of friends online
  524. String[] online = message.substring(6,message.length()).split(",\\s*");
  525. if(!online[0].equals("none"))
  526. { for(int i = 0; i < online.length; i++)
  527. changeFriends(online[i], true);
  528. }
  529. // output message in output area
  530.  
  531. addOutput("Your Friends Online: "+ message.substring(6,message.length()-1));
  532. }
  533. else
  534. // output message in output area
  535. addOutput(message);
  536. } // end else
  537. } // end else
  538. } // end else
  539. } // end while
  540. } // end else
  541. } // end try
  542. catch(IOException e) // thrown by method readObject
  543. { System.out.println(e);
  544. System.exit(1);
  545. }
  546. catch(ClassNotFoundException e) // thrown by method readObject
  547. { System.out.println(e);
  548. System.exit(1);
  549. }
  550. } // end method run
  551. } // end of class Chat_ClientThread
  552.  
  553. private class NameButtonHandler implements ActionListener
  554. { // if any of the name buttons are clicked execution will continue in this method
  555. public void actionPerformed(ActionEvent e)
  556. { int pos = -1;
  557. // loop to identify which of the name buttons were clicked
  558. for(int r = 0; r < nameButtons.length; r++)
  559. { if(e.getSource() == nameButtons[r])
  560. pos = r;
  561. }
  562. // add this friend's name to recipients list
  563. recipients += names[pos] + ",";
  564. if(pos == names.length - 1)
  565. /* you have chosen to send the message to all
  566. friends - change the colour of all the name buttons */
  567. changeNameButtons(Color.RED);
  568. else
  569. /* you have chosen to send the message to an individual
  570. friend - change the colour of this friends name button */
  571. changeNameButton(pos, Color.RED);
  572. }
  573. } // end of class NameButtonHandler
  574.  
  575. private class ImageButtonHandler implements ActionListener
  576. { // if any of the image buttons are clicked execution will continue in this method
  577. public void actionPerformed(ActionEvent e)
  578. { int pos = -1;
  579. // loop to identify which of the buttons were clicked
  580. for(int r = 0; r < imageButtons.length; r++)
  581. { if(e.getSource() == imageButtons[r])
  582. pos = r;
  583. }
  584. try
  585. { // retrieve the appropriate image from the array
  586. StyleConstants.setIcon(style, images[pos]);
  587. // add the image to the text input area
  588. docInputArea.insertString(docInputArea.getLength(), " $" + pos + " ", style);
  589. }
  590. catch(BadLocationException ee)
  591. { System.out.println(ee);
  592. System.exit(1);
  593. }
  594. }
  595. } // end of class ImageButtonHandler
  596.  
  597. private class ButtonHandler implements ActionListener
  598. { // if the logon or send buttons are clicked execution will continue in this method
  599. public void actionPerformed(ActionEvent e)
  600. { if(e.getSource() == logonButton)
  601. /* if the logon button is clicked call method to
  602. send the login details to the server */
  603. sendLoginDetails();
  604.  
  605. else if(e.getSource() == saveConvo)
  606. {
  607. //Will save chat log
  608. saveLog();
  609. addOutput("Saved Chatlog");
  610.  
  611. }
  612. else if(e.getSource() == Leave)
  613. {
  614. // Will Disconnect
  615. sendMessage("quit");
  616. }
  617.  
  618.  
  619. else
  620. { if(e.getSource() == sendButton)
  621. /* if the send button is clicked call method to
  622. send the message to the server */
  623. sendMessage(inputArea.getText());
  624. }
  625. }
  626. } // end of class ButtonHandler
  627. } // end of class Chat_Client
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement