-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatClient.java
More file actions
379 lines (327 loc) · 13.2 KB
/
ChatClient.java
File metadata and controls
379 lines (327 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
//Jonathan Nelson
//ChatClient.java
import java.util.*;
import java.io.*;
import java.net.*;
import javax.swing.text.*;
import java.awt.event.*;
public class ChatClient extends javax.swing.JFrame {
private static Socket socket;
private String serverAddress;
private int port = 1850;
private static InputStream in = null;
private static OutputStream out = null;
private static PrintWriter pout = null;
private static BufferedReader console = null;
private static BufferedReader inReader = null;
//private static String inMessage = null;
private static String outMessage = null;
private static boolean nowConnected = false;
/**
* Creates new form ChatClient
*/
public ChatClient() {
initComponents();
//setDoubleBuffered(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
serverName = new javax.swing.JTextField();
serverLabel = new javax.swing.JLabel();
uNameLabel = new javax.swing.JLabel();
uName = new javax.swing.JTextField();
connectButton = new javax.swing.JButton();
jSplitPane1 = new javax.swing.JSplitPane();
jScrollPane1 = new javax.swing.JScrollPane();
chatLogArea = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
userListArea = new javax.swing.JTextArea();
messageText = new javax.swing.JTextField();
sendButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
serverLabel.setText("Server");
uNameLabel.setText("User Name");
uName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
uNameActionPerformed(evt);
}
});
connectButton.setText("Connect");
connectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
connectButtonActionPerformed(evt);
}
});
jSplitPane1.setDividerLocation(600);
chatLogArea.setColumns(20);
chatLogArea.setRows(5);
jScrollPane1.setViewportView(chatLogArea);
jSplitPane1.setLeftComponent(jScrollPane1);
userListArea.setColumns(20);
userListArea.setRows(5);
jScrollPane2.setViewportView(userListArea);
jSplitPane1.setRightComponent(jScrollPane2);
//enable double buffereing on the scroll panes
//jScrollPane1.setDoubleBufferd(true);
//jScrollPane2.setDoubleBufferd(true);
messageText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
messageTextActionPerformed(evt);
}
});
sendButton.setText("Send");
sendButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(serverLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(serverName, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(75, 75, 75)
.addComponent(uNameLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(uName, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 253, Short.MAX_VALUE)
.addComponent(connectButton))
.addGroup(layout.createSequentialGroup()
.addComponent(messageText)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(sendButton)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(serverName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(serverLabel)
.addComponent(uNameLabel)
.addComponent(uName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(connectButton))
.addGap(18, 18, 18)
.addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 532, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(messageText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sendButton))
.addContainerGap())
);
jScrollPane1.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener(){
public void adjustmentValueChanged(AdjustmentEvent e){
chatLogArea.select(chatLogArea.getHeight()+100000,0);
}});
pack();
}// </editor-fold>
private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (messageText.getText() != null) {
String message = messageText.getText();
messageText.setText("");
sendMsg(message);
}
}
private void uNameActionPerformed(java.awt.event.ActionEvent evt) {
doConnectDisconnect();
}
private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {
doConnectDisconnect();
}
private void messageTextActionPerformed(java.awt.event.ActionEvent evt) {
if (messageText.getText() != null) {
String message = messageText.getText();
messageText.setText("");
sendMsg(message);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) throws Exception {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChatClient().setVisible(true);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
//hope and pray
}
DefaultCaret caret = (DefaultCaret)chatLogArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
//System.out.println("main() called");
while (true) {
//System.out.println("Checking to see if we are connected");
if (nowConnected) {
//System.out.println("main() still connected");
try {
if (inReader.ready()) {
//System.out.println("reading line from socket");
String inMessage = inReader.readLine();
//System.out.println(inMessage);
if (inMessage.startsWith("USER")) {
sendMsg(uName.getText());
} else if (inMessage.startsWith("WELCOME")) {
writeLog("Connection successful");
messageText.requestFocus();
} else if (inMessage.startsWith("GOODBYE")) {
if (inMessage.endsWith("BADUSER")) {
writeLog("That username is already in use");
} else if (inMessage.endsWith("TIMEOUT")) {
writeLog("The connection timed out.");
} else if (inMessage.endsWith("SHUTDOWN")) {
writeLog("The server is shutting down.");
}
writeLog("Server has closed the connection");
disconnect();
inMessage = null;
} else if (inMessage.startsWith("LIST")) {
updateUserList(inMessage);
} else {
//System.out.println("Message was not a control message");
writeLog(inMessage);
}
}
} catch (IOException e) {
//Under heavy load the server seems to forget about some users
System.err.println("Error accessing BufferedReader inReader");
writeLog("Error trying to read from the connection, trying to reconnect");
disconnect();
connect();
}
}
Thread.sleep(100);
}
}
private void doConnectDisconnect() {
if (connectButton.getText().equals("Connect"))
connect();
else
disconnect();
}
private static void connect() {
if (connectButton.getText().equals("Connect")) {
try {
if (!uName.getText().equals("") && !serverName.getText().equals("") ) {
//Disable access to buttons and text fields
connectButton.setText("Disconnect");
serverName.disable();
serverName.updateUI();
uName.disable();
uName.updateUI();
connectButton.disable();
writeLog("Connecting to " + serverName.getText() + " on port 1850");
socket = new Socket(serverName.getText(), 1850);
//socket.setKeepAlive();
in = socket.getInputStream();
out = socket.getOutputStream();
pout = new PrintWriter( out, true);
console = new BufferedReader( new InputStreamReader(System.in));
inReader = new BufferedReader(new InputStreamReader(in));
outMessage = new String();
//inMessage = new String();
connectButton.enable();
nowConnected = true;
} else {
writeLog("Server address and username can not be blank");
}
} catch (Exception e) {
//This will catch both IOExceptions as well as HostNotFoundExceptions
writeLog("Cannot connect to host");
//Enable access to buttons and text fields
connectButton.setText("Connect");
serverName.enable();
serverName.updateUI();
uName.enable();
uName.updateUI();
connectButton.enable();
}
}
}
private static void disconnect() {
if (connectButton.getText().equals("Disconnect")) {
writeLog("Disconnecting from server");
try {
sendMsg("DISCONNECT");
socket.close();
updateUserList("");
} catch (IOException e) {
//It's fine if we can't send the DISCONNECT message.
} finally {
in = null;
out = null;
pout = null;
socket = null;
console = null;
inReader = null;
outMessage = null;
nowConnected = false;
//Enable access to buttons and text fields
connectButton.setText("Connect");
serverName.enable();
serverName.updateUI();
uName.enable();
uName.updateUI();
connectButton.enable();
}
}
}
private static void sendMsg(String message) {
if (nowConnected && pout != null) {
pout.println(message);
}
}
private static void writeLog(String line) {
//DefaultCaret caret = (DefaultCaret)chatLogArea.getCaret();
//caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
if (line != null || !line.equals(""));
chatLogArea.append(line + "\n");
}
private static void updateUserList(String users) {
//System.out.println("updating user list");
//The first 5 characters of the string will be "LIST "
if (users != null) {
if (users.equals("")) {
userListArea.setText("");
} else {
users = users.substring(5, users.length());
StringTokenizer tokens = new StringTokenizer(users);
userListArea.setText("");
while (tokens.hasMoreTokens()) {
userListArea.append(tokens.nextToken() + "\n");
}
}
}
}
// Variables declaration - do not modify
private static javax.swing.JTextArea chatLogArea;
private static javax.swing.JButton connectButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSplitPane jSplitPane1;
private static javax.swing.JTextField messageText;
private javax.swing.JButton sendButton;
private javax.swing.JLabel serverLabel;
private static javax.swing.JTextField serverName;
private static javax.swing.JTextField uName;
private javax.swing.JLabel uNameLabel;
private static javax.swing.JTextArea userListArea;
// End of variables declaration
}