View Javadoc

1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
18   *
19   */
20  package org.apache.mina.example.chat.client;
21  
22  import java.awt.BorderLayout;
23  import java.awt.Dimension;
24  import java.awt.event.ActionEvent;
25  import java.awt.event.ActionListener;
26  import java.net.InetSocketAddress;
27  import java.net.SocketAddress;
28  
29  import javax.swing.AbstractAction;
30  import javax.swing.BorderFactory;
31  import javax.swing.Box;
32  import javax.swing.BoxLayout;
33  import javax.swing.JButton;
34  import javax.swing.JFrame;
35  import javax.swing.JLabel;
36  import javax.swing.JOptionPane;
37  import javax.swing.JPanel;
38  import javax.swing.JScrollBar;
39  import javax.swing.JTextArea;
40  import javax.swing.JTextField;
41  import javax.swing.border.EmptyBorder;
42  
43  import org.apache.mina.example.chat.client.SwingChatClientHandler.Callback;
44  import org.apache.mina.transport.socket.nio.NioSocketConnector;
45  
46  /**
47   * Simple chat client based on Swing & MINA that implements the chat protocol.
48   *
49   * @author The Apache MINA Project (dev@mina.apache.org)
50   * @version $Rev$, $Date$
51   */
52  public class SwingChatClient extends JFrame implements Callback {
53      private static final long serialVersionUID = 1538675161745436968L;
54  
55      private JTextField inputText;
56  
57      private JButton loginButton;
58  
59      private JButton quitButton;
60  
61      private JButton closeButton;
62  
63      private JTextField serverField;
64  
65      private JTextField nameField;
66  
67      private JTextArea area;
68  
69      private JScrollBar scroll;
70  
71      private ChatClientSupport client;
72  
73      private SwingChatClientHandler handler;
74  
75      private NioSocketConnector connector;
76  
77      public SwingChatClient() {
78          super("Chat Client based on Apache MINA");
79  
80          connector = new NioSocketConnector();
81  
82          loginButton = new JButton(new LoginAction());
83          loginButton.setText("Connect");
84          quitButton = new JButton(new LogoutAction());
85          quitButton.setText("Disconnect");
86          closeButton = new JButton(new QuitAction());
87          closeButton.setText("Quit");
88          inputText = new JTextField(30);
89          inputText.setAction(new BroadcastAction());
90          area = new JTextArea(10, 50);
91          area.setLineWrap(true);
92          area.setEditable(false);
93          scroll = new JScrollBar();
94          scroll.add(area);
95          nameField = new JTextField(10);
96          nameField.setEditable(false);
97          serverField = new JTextField(10);
98          serverField.setEditable(false);
99  
100         JPanel h = new JPanel();
101         h.setLayout(new BoxLayout(h, BoxLayout.LINE_AXIS));
102         h.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
103         JLabel nameLabel = new JLabel("Name: ");
104         JLabel serverLabel = new JLabel("Server: ");
105         h.add(nameLabel);
106         h.add(Box.createRigidArea(new Dimension(10, 0)));
107         h.add(nameField);
108         h.add(Box.createRigidArea(new Dimension(10, 0)));
109         h.add(Box.createHorizontalGlue());
110         h.add(Box.createRigidArea(new Dimension(10, 0)));
111         h.add(serverLabel);
112         h.add(Box.createRigidArea(new Dimension(10, 0)));
113         h.add(serverField);
114 
115         JPanel p = new JPanel();
116         p.setLayout(new BoxLayout(p, BoxLayout.LINE_AXIS));
117         p.setBorder(new EmptyBorder(10, 10, 10, 10));
118 
119         JPanel left = new JPanel();
120         left.setLayout(new BoxLayout(left, BoxLayout.PAGE_AXIS));
121         left.add(area);
122         left.add(Box.createRigidArea(new Dimension(0, 5)));
123         left.add(Box.createHorizontalGlue());
124         left.add(inputText);
125 
126         JPanel right = new JPanel();
127         right.setLayout(new BoxLayout(right, BoxLayout.PAGE_AXIS));
128         right.add(loginButton);
129         right.add(Box.createRigidArea(new Dimension(0, 5)));
130         right.add(quitButton);
131         right.add(Box.createHorizontalGlue());
132         right.add(Box.createRigidArea(new Dimension(0, 25)));
133         right.add(closeButton);
134 
135         p.add(left);
136         p.add(Box.createRigidArea(new Dimension(10, 0)));
137         p.add(right);
138 
139         getContentPane().add(h, BorderLayout.NORTH);
140         getContentPane().add(p);
141 
142         closeButton.addActionListener(new ActionListener() {
143             public void actionPerformed(ActionEvent e) {
144                 client.quit();
145                 connector.dispose(); 
146                 dispose();
147             }
148         });
149         setLoggedOut();
150         setDefaultCloseOperation(EXIT_ON_CLOSE);
151     }
152 
153     public class LoginAction extends AbstractAction {
154         private static final long serialVersionUID = 3596719854773863244L;
155 
156         public void actionPerformed(ActionEvent e) {
157 
158             ConnectDialog dialog = new ConnectDialog(SwingChatClient.this);
159             dialog.pack();
160             dialog.setVisible(true);
161 
162             if (dialog.isCancelled()) {
163                 return;
164             }
165 
166             SocketAddress address = parseSocketAddress(dialog
167                     .getServerAddress());
168             String name = dialog.getUsername();
169 
170             handler = new SwingChatClientHandler(SwingChatClient.this);
171             client = new ChatClientSupport(name, handler);
172             nameField.setText(name);
173             serverField.setText(dialog.getServerAddress());
174 
175             if (!client.connect(connector, address, dialog.isUseSsl())) {
176                 JOptionPane.showMessageDialog(SwingChatClient.this,
177                         "Could not connect to " + dialog.getServerAddress()
178                                 + ". ");
179             }
180         }
181     }
182 
183     private class LogoutAction extends AbstractAction {
184         private static final long serialVersionUID = 1655297424639924560L;
185 
186         public void actionPerformed(ActionEvent e) {
187             try {
188                 client.quit();
189                 setLoggedOut();
190             } catch (Exception e1) {
191                 JOptionPane.showMessageDialog(SwingChatClient.this,
192                         "Session could not be closed.");
193             }
194         }
195     }
196 
197     private class BroadcastAction extends AbstractAction {
198         /**
199          *
200          */
201         private static final long serialVersionUID = -6276019615521905411L;
202 
203         public void actionPerformed(ActionEvent e) {
204             client.broadcast(inputText.getText());
205             inputText.setText("");
206         }
207     }
208 
209     private class QuitAction extends AbstractAction {
210         private static final long serialVersionUID = -6389802816912005370L;
211 
212         public void actionPerformed(ActionEvent e) {
213             if (client != null) {
214                 client.quit();
215             }
216             SwingChatClient.this.dispose();
217         }
218     }
219 
220     private void setLoggedOut() {
221         inputText.setEnabled(false);
222         quitButton.setEnabled(false);
223         loginButton.setEnabled(true);
224     }
225 
226     private void setLoggedIn() {
227         area.setText("");
228         inputText.setEnabled(true);
229         quitButton.setEnabled(true);
230         loginButton.setEnabled(false);
231     }
232 
233     private void append(String text) {
234         area.append(text);
235     }
236 
237     private void notifyError(String message) {
238         JOptionPane.showMessageDialog(this, message);
239     }
240 
241     private SocketAddress parseSocketAddress(String s) {
242         s = s.trim();
243         int colonIndex = s.indexOf(":");
244         if (colonIndex > 0) {
245             String host = s.substring(0, colonIndex);
246             int port = parsePort(s.substring(colonIndex + 1));
247             return new InetSocketAddress(host, port);
248         } else {
249             int port = parsePort(s.substring(colonIndex + 1));
250             return new InetSocketAddress(port);
251         }
252     }
253 
254     private int parsePort(String s) {
255         try {
256             return Integer.parseInt(s);
257         } catch (NumberFormatException nfe) {
258             throw new IllegalArgumentException("Illegal port number: " + s);
259         }
260     }
261 
262     public void connected() {
263         //client.login();
264     }
265 
266     public void disconnected() {
267         append("Connection closed.\n");
268         setLoggedOut();
269     }
270 
271     public void error(String message) {
272         notifyError(message + "\n");
273     }
274 
275     public void loggedIn() {
276         setLoggedIn();
277         append("You have joined the chat session.\n");
278     }
279 
280     public void loggedOut() {
281         append("You have left the chat session.\n");
282         setLoggedOut();
283     }
284 
285     public void messageReceived(String message) {
286         append(message + "\n");
287     }
288 
289     public static void main(String[] args) {
290         SwingChatClient client = new SwingChatClient();
291         client.pack();
292         client.setVisible(true);
293     }
294 }