Advertisement
Guest User

andrexpablo

a guest
Dec 11th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.85 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3. import java.net.*;
  4. import javax.swing.*;
  5. import java.awt.*;
  6. import java.awt.event.*;
  7. import static java.lang.System.out;
  8. public class ChatClient extends JFrame implements ActionListener {
  9. String uname;
  10. PrintWriter pw;
  11. BufferedReader br;
  12. JTextArea taMessages;
  13. JTextField tfInput;
  14. JButton btnSend,btnExit;
  15. Socket client;
  16.  
  17. public ChatClient(String uname,String servername) throws Exception {
  18. super(uname); // set title for frame
  19. this.uname = uname;
  20. client = new Socket(servername,9999);
  21. br = new BufferedReader( new InputStreamReader( client.getInputStream()) ) ;
  22. pw = new PrintWriter(client.getOutputStream(),true);
  23. pw.println(uname); // send name to server
  24. buildInterface();
  25. new MessagesThread().start(); // create thread to listen for messages
  26. }
  27. public void buildInterface() {
  28. btnSend = new JButton("Invia");
  29. btnExit = new JButton("Esci");
  30. taMessages = new JTextArea();
  31. taMessages.setRows(10);
  32. taMessages.setColumns(50);
  33. taMessages.setEditable(false);
  34. tfInput = new JTextField(50);
  35. JScrollPane sp = new JScrollPane(taMessages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
  36. JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
  37. add(sp,"Center");
  38. JPanel bp = new JPanel( new FlowLayout());
  39. bp.add(tfInput);
  40. bp.add(btnSend);
  41. bp.add(btnExit);
  42. add(bp,"South");
  43. btnSend.addActionListener(this);
  44. btnExit.addActionListener(this);
  45. setSize(500,300);
  46. setVisible(true);
  47. pack();
  48. }
  49. public void actionPerformed(ActionEvent evt) {
  50. if ( evt.getSource() == btnExit ) {
  51. pw.println("end"); // send end to server so that server knows about the termination
  52. System.exit(0);
  53. } else {
  54. // send message to server
  55. pw.println(tfInput.getText());
  56. }
  57. }
  58.  
  59. public static void main(String ... args) {
  60.  
  61. // take username from user
  62. String name = JOptionPane.showInputDialog(null,"Inserisci il tuo nome :", "Username",
  63. JOptionPane.PLAIN_MESSAGE);
  64. String servername = "localhost";
  65. try {
  66. new ChatClient( name ,servername);
  67. } catch(Exception ex) {
  68. out.println( "Errore --> " + ex.getMessage());
  69. }
  70. } // end of main
  71.  
  72. // inner class for Messages Thread
  73. class MessagesThread extends Thread {
  74. public void run() {
  75. String line;
  76. try {
  77. while(true) {
  78. line = br.readLine();
  79. taMessages.append(line + "\n");
  80. } // end of while
  81. } catch(Exception ex) {}
  82. }
  83. }
  84. } // end of client
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement