-
Notifications
You must be signed in to change notification settings - Fork 1
/
server_frame.java
305 lines (264 loc) · 10.3 KB
/
server_frame.java
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
package chat_server;
import java.io.*;
import java.net.*;
import java.util.*;
public class server_frame extends javax.swing.JFrame
{
ArrayList clientOutputStreams;
ArrayList<String> users;
public class ClientHandler implements Runnable
{
BufferedReader reader;
Socket websocket;
PrintWriter client;
public ClientHandler(Socket clientSocket, PrintWriter user)
{
client = user;
try
{
websocket = clientSocket;
InputStreamReader isReader = new InputStreamReader(websocket.getInputStream());
reader = new BufferedReader(isReader);
}
catch (Exception ex)
{
//ta_chat.append("Erro inesperado... \n");
System.out.println("[Servidor] Erro inesperado");
}
}
@Override
public void run()
{
String message, connect = "Connect", disconnect = "Disconnect", chat = "Chat" ;
String[] data;
try
{
while ((message = reader.readLine()) != null)
{
//ta_chat.append("Recebida: " + message + "\n");
data = message.split(":");
for (String token:data)
{
ta_chat.append(token + "\n");
}
if (data[2].equals(connect))
{
tellEveryone((data[0] + ":" + data[1] + ":" + chat));
userAdd(data[0]);
}
else if (data[2].equals(disconnect))
{
tellEveryone((data[0] + ":has disconnected." + ":" + chat));
userRemove(data[0]);
}
else if (data[2].equals(chat))
{
tellEveryone(message);
}
else
{
//ta_chat.append("No Conditions were met. \n");
System.out.println("[Servidor] Nenhuma conexão foi encontrada");
}
}
}
catch (Exception ex)
{
//ta_chat.append("Lost a connection. \n");
System.out.println("[Servidor] conexão perdida");
ex.printStackTrace();
clientOutputStreams.remove(client);
}
}
}
public server_frame()
{
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
ta_chat = new javax.swing.JTextArea();
b_start = new javax.swing.JButton();
b_end = new javax.swing.JButton();
b_users = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Chat - Server's frame");
setName("server"); // NOI18N
setResizable(false);
ta_chat.setColumns(20);
ta_chat.setRows(5);
jScrollPane1.setViewportView(ta_chat);
b_start.setText("START");
b_start.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_startActionPerformed(evt);
}
});
b_end.setText("END");
b_end.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_endActionPerformed(evt);
}
});
b_users.setText("Online Users");
b_users.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_usersActionPerformed(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(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(b_start, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b_end, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(b_users)
.addGap(0, 128, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(b_start)
.addComponent(b_users)
.addComponent(b_end))
.addGap(20, 20, 20))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void b_endActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_endActionPerformed
try
{
Thread.sleep(5000); //5000 milliseconds is five second.
}
catch(InterruptedException ex) {Thread.currentThread().interrupt();}
tellEveryone("Server:Desconectando todos os usuários.\n:Chat");
//ta_chat.append("Servidor desconectando... \n");
System.out.println("Servidor desconectando");
ta_chat.setText("");
}//GEN-LAST:event_b_endActionPerformed
private void b_startActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_startActionPerformed
Thread starter = new Thread(new ServerStart());
starter.start();
//ta_chat.append("O servidor de mensagem foi iniciado\n");
System.out.println("O servidor de mensagem foi iniciado");
}//GEN-LAST:event_b_startActionPerformed
private void b_usersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_usersActionPerformed
//ta_chat.append("\n Usuários online : \n");
System.out.println("Usuários online : \n");
for (String current_user : users)
{
System.out.println(current_user);
//ta_chat.append(current_user);
//ta_chat.append("\n");
}
}//GEN-LAST:event_b_usersActionPerformed
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable()
{
@Override
public void run() {
new server_frame().setVisible(true);
}
});
}
public class ServerStart implements Runnable
{
@Override
public void run()
{
clientOutputStreams = new ArrayList();
users = new ArrayList();
try
{
ServerSocket serverSock = new ServerSocket(3000);
while (true)
{
Socket clientSock = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSock.getOutputStream());
clientOutputStreams.add(writer);
Thread listener = new Thread(new ClientHandler(clientSock, writer));
listener.start();
ta_chat.append("Recebemos uma conexão. \n");
}
}
catch (Exception ex)
{
ta_chat.append("Error making a connection. \n");
System.out.println("Erro ao fazer conexão");
}
}
}
public void userAdd (String data)
{
String message, add = ": :Connect", done = "Server: :Done", name = data;
//ta_chat.append("Before " + name + " added. \n");
users.add(name);
//ta_chat.append("After " + name + " added. \n");
String[] tempList = new String[(users.size())];
users.toArray(tempList);
System.out.println("[Servidor] O usuário " + name + " foi adicionado ao chat");
for (String token:tempList)
{
message = (token + add);
tellEveryone(message);
}
tellEveryone(done);
}
public void userRemove (String data)
{
String message, add = ": :Connect", done = "Server: :Done", name = data;
users.remove(name);
String[] tempList = new String[(users.size())];
users.toArray(tempList);
for (String token:tempList)
{
message = (token + add);
tellEveryone(message);
}
tellEveryone(done);
}
public void tellEveryone(String message)
{
Iterator it = clientOutputStreams.iterator();
while (it.hasNext())
{
try
{
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
//ta_chat.append("Sending: " + message + "\n");
System.out.println("Sending: " + message + "\n");
writer.flush();
ta_chat.setCaretPosition(ta_chat.getDocument().getLength());
}
catch (Exception ex)
{
//ta_chat.append("Error telling everyone. \n");
System.out.println("Erro ao enviar mensagem aos usuários");
}
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton b_end;
private javax.swing.JButton b_start;
private javax.swing.JButton b_users;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea ta_chat;
// End of variables declaration//GEN-END:variables
}