Guest User

ChatClient

a guest
Aug 10th, 2014
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.23 KB | None | 0 0
  1. package chat;
  2.  
  3. import java.awt.GridBagConstraints;
  4. import java.awt.GridBagLayout;
  5. import java.awt.event.ActionEvent;
  6. import java.awt.event.ActionListener;
  7. import java.awt.event.WindowAdapter;
  8. import java.awt.event.WindowEvent;
  9. import java.io.BufferedReader;
  10. import java.io.IOException;
  11. import java.io.InputStreamReader;
  12. import java.io.PrintWriter;
  13. import java.net.ServerSocket;
  14. import java.net.Socket;
  15.  
  16. import javax.swing.JButton;
  17. import javax.swing.JFrame;
  18. import javax.swing.JOptionPane;
  19. import javax.swing.JPanel;
  20. import javax.swing.JScrollPane;
  21. import javax.swing.JTextArea;
  22. import javax.swing.JTextField;
  23.  
  24. public class ChatClient {
  25.  
  26. //communication variables
  27. BufferedReader in;
  28. PrintWriter out;
  29. String username;
  30. public static final int PORT = 9001;
  31.  
  32. //GUI variables
  33. JFrame frame;
  34. JPanel panel;
  35. JTextField inputField;
  36. JTextArea messageArea;
  37. JButton clientButton;
  38. JButton serverButton;
  39.  
  40. ChatServer localServer;
  41. ServerSocket listener;
  42.  
  43. //create GUI
  44. public ChatClient () {
  45.  
  46. //panel and layout manager
  47. panel = new JPanel(new GridBagLayout());
  48. GridBagConstraints c = new GridBagConstraints();
  49.  
  50. //create and add input field
  51. c.gridwidth=2;
  52. c.fill = GridBagConstraints.HORIZONTAL;
  53. inputField = new JTextField(40);
  54. inputField.setEditable(false);
  55.  
  56. //send text when enter is pressed and clear input field
  57. inputField.addActionListener(new ActionListener() {
  58.  
  59. public void actionPerformed(ActionEvent e) {
  60. out.println(inputField.getText());
  61. inputField.setText("");
  62. }
  63.  
  64. });
  65. panel.add(inputField, c);
  66.  
  67. //create and add message area
  68. c.gridy=1;
  69. c.weighty=1;
  70. c.fill = GridBagConstraints.BOTH;
  71. messageArea = new JTextArea(8,40);
  72. messageArea.setEditable(false);
  73. panel.add(new JScrollPane(messageArea), c);
  74.  
  75. //create and add "Connect" button
  76. c.gridy=2;
  77. c.gridwidth=1;
  78. c.fill = GridBagConstraints.HORIZONTAL;
  79. c.weightx=1;
  80. c.weighty=0;
  81. clientButton = new JButton("Connect to chatroom");
  82.  
  83. //when pressed, connect to server on separate thread
  84. clientButton.addActionListener(new ActionListener() {
  85.  
  86. public void actionPerformed (ActionEvent e) {
  87.  
  88. if (in==null && out==null) {
  89.  
  90. new Thread(new Runnable() {
  91.  
  92. public void run() {
  93.  
  94. receiveInput();
  95.  
  96. }
  97.  
  98. }).start();
  99.  
  100. } else if (in!=null&&out!=null) {
  101. out.println("DISCONNECTING");
  102. }
  103.  
  104. }
  105.  
  106. });
  107. panel.add(clientButton, c);
  108.  
  109. //create and add "Start server" button
  110. serverButton = new JButton("Start chatroom");
  111. serverButton.addActionListener(new ActionListener() {
  112. public void actionPerformed (ActionEvent e) {
  113.  
  114. new Thread(new Runnable() {
  115.  
  116. public void run() {
  117.  
  118. //start server
  119. localServer = new ChatServer();
  120.  
  121. new Thread(new Runnable() {
  122.  
  123. public void run() {
  124.  
  125. if (!localServer.running) {
  126. try {
  127. listener.close();
  128. } catch (IOException e) {
  129. // TODO Auto-generated catch block
  130. e.printStackTrace();
  131. }
  132. }
  133.  
  134. }
  135.  
  136. }).start();
  137.  
  138. //new listener on port
  139. try {
  140. listener = new ServerSocket(PORT);
  141. //continuously accept new clients
  142. while (localServer.running) {
  143. localServer.new Handler(listener.accept()).start();
  144. }
  145. localServer = null;
  146. } catch (IOException serverException) {
  147. serverException.printStackTrace();
  148. } finally {
  149. try {
  150. listener.close();
  151. } catch (IOException e) {
  152. System.out.println("Couldn't close socket");
  153. }
  154. }
  155.  
  156. }
  157.  
  158. }).start();
  159. }
  160. });
  161. panel.add(serverButton, c);
  162.  
  163. //create and show frame
  164. frame = new JFrame("George's Chat Program");
  165. frame.add(panel);
  166. frame.pack();
  167. frame.setLocationRelativeTo(null);
  168. frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  169.  
  170. //when "X" pressed
  171. frame.addWindowListener(new WindowAdapter() {
  172. public void windowClosing (WindowEvent e) {
  173.  
  174. if (in==null&&out==null) {
  175. System.exit(0);
  176. }
  177.  
  178. out.println("DISCONNECTING");
  179. try {
  180. Thread.sleep(500);
  181. } catch (InterruptedException e1) {
  182. e1.printStackTrace();
  183. }
  184. System.exit(0);
  185.  
  186. }
  187. });
  188. frame.setVisible(true);
  189.  
  190. }
  191.  
  192. //get desired address from user
  193. private String getServerAddress () {
  194.  
  195. return JOptionPane.showInputDialog(
  196. frame,
  197. "Enter IP Address of the Server:",
  198. "Welcome to George's Chat Program",
  199. JOptionPane.QUESTION_MESSAGE);
  200.  
  201. }
  202.  
  203. //get desired screen name from user
  204. private String getName () {
  205.  
  206. return JOptionPane.showInputDialog(
  207. frame,
  208. "Choose a screen name:",
  209. "Screen name selection",
  210. JOptionPane.PLAIN_MESSAGE);
  211.  
  212. }
  213.  
  214. //connects to server then begins processing input
  215. private void receiveInput() {
  216.  
  217. //Make connection and initialize streams (try-with-resources YES)
  218. try (Socket socket = new Socket(getServerAddress(), PORT)) {
  219.  
  220. in = new BufferedReader(new InputStreamReader(
  221. socket.getInputStream()));
  222. out = new PrintWriter(socket.getOutputStream(), true);
  223. clientButton.setText("Disconnect from chatroom");
  224. serverButton.setEnabled(false);
  225.  
  226. // Process all messages from server, according to the protocol.
  227. while (true) {
  228.  
  229. String line = in.readLine();
  230.  
  231. if (line.startsWith("SUBMITNAME")) {
  232. while ((username=getName())==null||username.equals("")) {
  233. JOptionPane.showMessageDialog(frame,"Username cannot be blank.");
  234. }
  235. out.println(username);
  236. } else if (line.startsWith("NAMEACCEPTED")) {
  237. inputField.setEditable(true);
  238. } else if (line.startsWith("MESSAGE")) {
  239. messageArea.append(line.substring(8) + "\n");
  240. } else if (line.startsWith("BYE")) {
  241. break;
  242. }
  243.  
  244. }
  245.  
  246. } catch (IOException e) {
  247.  
  248. JOptionPane.showMessageDialog(frame, "No chat server is running at the specified address.");
  249.  
  250. //server has closed or user has disconnected
  251. } finally {
  252.  
  253. in = null;
  254. out = null;
  255. clientButton.setText("Connect to chatroom");
  256. serverButton.setEnabled(true);
  257. inputField.setEditable(false);
  258. messageArea.setText("");
  259.  
  260. }
  261.  
  262. }
  263.  
  264. public static void main(String[] args) {
  265.  
  266. new ChatClient();
  267.  
  268. }
  269.  
  270. }
Advertisement
Add Comment
Please, Sign In to add comment